Skip to content

Instantly share code, notes, and snippets.

@pradykaushik
Created October 29, 2020 01:03
Show Gist options
  • Save pradykaushik/a73e2254763ecaa9c3f8f7ac7856db0e to your computer and use it in GitHub Desktop.
Save pradykaushik/a73e2254763ecaa9c3f8f7ac7856db0e to your computer and use it in GitHub Desktop.
Design for validation
public class Validation {
// Driver code.
public static void main(String... args) throws Exception {
Person p = new Person("john", 25);
Person p2 = new Person("", 25);
}
}
// Validator interface would typically be placed in the utility folder.
interface Validator {
void run() throws Exception;
}
// ValidatorUtil would typically be placed in the utility folder.
class ValidationUtil {
public static void validate(String baseErrMsg, Validator... validators) throws Exception {
for (Validator v : validators) {
try {
v.run();
} catch (Exception e) {
throw new Exception (baseErrMsg, e);
}
}
}
}
// Person class.
class Person {
private String name;
private int age;
// Wrapped the validators in an inner class.
// However, you could also just have them as private static methods in the Person class that return Validator.
private static class PersonValidator {
static Validator nameValidator(Person p) {
return () -> {
if (p.name == "") throw new Exception("invalid name");
};
}
static Validator ageValidator(Person p) {
return () -> {
if (p.age < 0) throw new Exception("invalid age");
};
}
}
// A person object is successfully instantiated only if the validation succeeds.
// Otherwise, an exception is thrown.
public Person(String name, int age) throws Exception {
this.name = name;
this.age = age;
ValidationUtil.validate("invalid person",
PersonValidator.nameValidator(this),
PersonValidator.ageValidator(this));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment