lundi 1 mars 2021

Simplify validators with Java8

I have the following class:

public class Client{

    private String name;
    private LocalDate dateOfBirth;
}

And currently my validator method looks like:

 @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);

    }

How can I replace the ifs from my validation method using Java8 functional programming in order to make my code more readable?

Aucun commentaire:

Enregistrer un commentaire