使用Java8简化验证器

使用Java8简化验证器,java,validation,if-statement,functional-programming,Java,Validation,If Statement,Functional Programming,我有以下课程: public class Client{ private String name; private LocalDate dateOfBirth; } 目前,我的验证器方法如下所示: @Override public void validate(Client entity) throws ValidatorException { String exceptionMsg=""; if(entity.ge

我有以下课程:

public class Client{

    private String name;
    private LocalDate dateOfBirth;
}
目前,我的验证器方法如下所示:

 @Override
    public void validate(Client entity) throws ValidatorException {
        String exceptionMsg="";
        if(entity.getName().isEmpty())
            exceptionMsg+="Client name cannot be empty.";
        LocalDate clientDate = entity.getDateOfBirth();
        LocalDate now = LocalDate.now();
        Period difference = Period.between(clientDate, now); //difference between the dates is calculated
        if(difference.getYears() < 18)
            exceptionMsg += "Client must have at least 18 years";

        if(!exceptionMsg.isEmpty())
            throw new ValidatorException(exceptionMsg);

    }
@覆盖
public void validate(客户端实体)引发Validator异常{
字符串exceptionMsg=“”;
if(entity.getName().isEmpty())
exceptionMsg+=“客户端名称不能为空。”;
LocalDate clientDate=entity.getDateOfBirth();
LocalDate now=LocalDate.now();
Period difference=Period.between(clientDate,now);//计算日期之间的差异
if(差分.getYears()<18)
exceptionMsg+=“客户必须至少有18年”;
如果(!exceptionMsg.isEmpty())
抛出新的ValidatorException(exceptionMsg);
}

如何使用Java8函数式编程替换验证方法中的ifs,以使代码更具可读性?

对于使用java 8函数式编程功能的字符串,可以使用以下选项:

//检查空白或空字符串的步骤

    Predicate<String> isNull = (s) -> (s==null || s.equals(""));
//invoke Lambda
    boolean a=isNull.test(clientName);
谓词isNull=(s)->(s==null | | s.equals(“”);
//调用Lambda
布尔值a=isNull.test(clientName);
日期比较:

    Predicate<LocalDate> isLessDifference = (dt) -> ( Period.between( dt,     LocalDate.now()).getYears()<18) ; 
//invoke lambda
    boolean isLess = isLessDifference.test(d2t);
谓词isLessDifference=(dt)->(Period.between(dt,LocalDate.now()).getYears()