jdk8 新特性 Optional

​ JDK8新特性 :Optional(看似高大上 实则没卵用的东西)

github : https://github.com/abksrv/optional-chaining-comparison-if-else.git

​ Validator.java

package com.mpt.propertiesDemo.java8;

import java.util.Optional;

@FunctionalInterface
interface Validator {
    /**
     * Validate input String
     * 
     * @return An Optional containing error message or an empty Optional when
     *         validation is successful.
     */
    Optional validate(String input);
}

ValidationFailedObject.java

package com.mpt.propertiesDemo.java8;

/**
 * Details of a failed validation.
 * 
 * @author AbK
 *
 */
public class ValidationFailedObject {
    public ValidationFailedObject(String string) {
        this.message = string;
    }

    private String message;
}
package com.mpt.propertiesDemo.java8;

import java.util.Optional;

public class ChainedValidator implements Validator{

    private static final int MINIMUM_LENGTH = 8;

    public Optional validate(final String userInput) {
        return validateUsing(minimumLengthValidator(), userInput).map(Optional::of)
                .orElseGet(() -> validateUsing(numericCharactersValidator(),
                                userInput)).map(Optional::of)
                .orElseGet(() -> validateUsing(upperCaseCharactersValidator(),
                                userInput));
        /*return validateUsing(minimumLengthValidator(), userInput)
                .or(() -> validateUsing(numericCharactersValidator(), userInput))
                .or(() -> validateUsing(upperCaseCharactersValidator(), userInput));*/
    }

    private Validator numericCharactersValidator() {
        return input -> input.matches(".*\\d+.*") ? Optional.empty() : Optional
                .of(new ValidationFailedObject("Should contain at least a digit"));
    }

    private Validator upperCaseCharactersValidator() {
        return input -> input.matches(".*[A-Z]+.*") ? Optional.empty()
                : Optional.of(new ValidationFailedObject("Should contain an upper case letter"));
    }

    private Validator minimumLengthValidator() {
        return input -> (input != null && input.length() > MINIMUM_LENGTH) ? Optional
                .empty() : Optional.of(new ValidationFailedObject(
                "Required min. length at least " + MINIMUM_LENGTH + " characters."));
    }

    private Optional validateUsing(Validator validator,
            String userInput) {
        return validator.validate(userInput);
    }
    
    public static void main(String[] args) {
        Optional validate = new ChainedValidator().validate("123ZemenskyabC");
        validate.ifPresent(obj -> System.out.println(obj));
    }
}

虽然从语法层面上来说,这种操作是很繁琐,还不如if else嵌套来的方便,但是这段程序的思想方式还是很值得学习的,把对数字的验证,大写字母的验证,小写字母的验证用对象进行处理,这样在验证中可以携带错误信息。

你可能感兴趣的:(jdk8 新特性 Optional)