Created
October 8, 2014 16:18
-
-
Save scottashipp/2cd88d2cfdf935895dd5 to your computer and use it in GitHub Desktop.
Builder pattern example, Validator class
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
class Validator { | |
private Set<String> validationErrors; | |
private Map<String[], ValidationRule> validationRules; | |
private boolean validated = false; | |
Validator() { | |
validationRules = new HashMap<String[], ValidationRule>(); | |
validationErrors = new HashSet<String>(); | |
} | |
public void addValidationRule(ValidationRule newValidationRule, String... args) { | |
String[] argsAsArray = args; | |
validationRules.put(argsAsArray, newValidationRule); | |
} | |
public void validate() { | |
for(Map.Entry<String[], ValidationRule> entry : validationRules.entrySet()) { | |
String[] valuesToValidate = entry.getKey(); | |
ValidationRule rule = entry.getValue(); | |
for(int i = 0; i < valuesToValidate.length; i++) { | |
if(!rule.validate(valuesToValidate[i])) { | |
validationErrors.add(rule.getErrorMessage()); | |
} | |
} | |
} | |
validated = true; | |
} | |
public boolean hasValidationErrors() { | |
if(!validated) { | |
validate(); | |
} | |
return validationErrors.size() > 0; | |
} | |
public String[] getValidationErrors() { | |
if(!validated) { | |
validate(); | |
} | |
return validationErrors.toArray(new String[validationErrors.size()]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment