Last active
August 29, 2015 14:13
-
-
Save schaloner/ad815aa4c8e8c21b396b to your computer and use it in GitHub Desktop.
Apply a series of validations to an object using a stream, with subsequent validations only applied if earlier ones succeeded.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package be.objectify.example.validators; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.function.Function; | |
public class GenericValidator<T> implements Function<T, Boolean> { | |
private final List<Function<T, Boolean>> validators = new LinkedList<>(); | |
public GenericValidator(List<Function<T, Boolean>> validators) { | |
this.validators.addAll(validators); | |
} | |
@Override | |
public Boolean apply(final T toValidate) { | |
final boolean[] guard = {true}; | |
return validators.stream() | |
.filter(validator -> guard[0]) | |
.map(validator -> validator.apply(toValidate)) | |
.map(result -> { | |
guard[0] = result; | |
return result; | |
}) | |
.reduce(guard[0], (a, b) -> a && b); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package be.objectify.example.validators; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.function.Function; | |
import be.objectify.example.utils.StringUtils; | |
public class PersonValidator extends GenericValidator<Person> { | |
private static final List<Function<Person, Boolean>> VALIDATIONS = new LinkedList<>(); | |
static { | |
VALIDATIONS.add(person -> person != null); | |
VALIDATIONS.add(person -> StringUtils.isNotEmpty(person.givenName)); | |
VALIDATIONS.add(person -> StringUtils.isNotEmpty(person.familyName)); | |
VALIDATIONS.add(person -> person.gender != null); | |
} | |
public PersonValidator() { | |
super(VALIDATIONS); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment