Think of each test of the rule as an object, or as a strategy that returns whether the rule passes. Each test should implement the same IRuleCheck interface and return a RuleCheckResult, which indicates whether the test passed or the reason for the failure.
public interface IRuleCheck { public RuleCheckResult Check(Input input); public String Name(); } public class RuleCheckResult { private String _errorMessage; public RuleCheckResult(){}
Then you can simply create a list of rules and skip them, and either jump when it fails, or compile the list of failures.
for (IRuleCheck check : checkList) { System.out.println("checking: " + check.Name()); RuleCheckResult result = check.Check(input); if(!result.Passed()) { System.out.println("FAILED: " + check.Name()+ " - " + result.ErrorMessage()); //either jump out and return result or add it to failure list to return later. } }
And the advantage of using the interface is that the checks can be as complex or simple as necessary, and you can create arbitrary lists to check any combination of rules in any order.
source share