Implement the rules as a chain of responsibility :
ruleFoo -> ruleBar -> ruleFooBar -> ....
The chain has to be ordered according to the rule precedence and each element of the chain (the rule here) is processed to detect a match. As soon as a rule matches the rule performs the suitable action and the chain process is stopped.
Here a very simple implementation that takes advantage of java 8 stream (that is a little different of the original GOF pattern but I Like it because that is lighter to implement).
public interface ResponseRule {
boolean match(Response response);
void performAction();
}
public class RuleFoo implements ReponseRule {
public boolean match(Response response){
return response.getStatusCode() == HttpStatus.BAD_REQUEST && response.getBody().code == 1;
}
public void performAction(){
// do the action
}
}
public class RuleBar implements AbstractReponseRule {
public boolean match(Response response){
return response.getStatusCode() == HttpStatus.BAD_REQUEST && response.getBody() != null;
}
public void performAction(){
// do the action
}
}
And how use them :
Response response = ...;
List<ResponseRule> rules = new ArrayList<>();
rules.add(new RuleFoo(), new RuleBar());
rules.stream()
.filter(rule -> rule.match(response))
.findFirst()
.ifPresent(ResponseRule::performAction);
Note that if rules execution could be accumulated, that would require a small change :
rules.stream()
.filter(rule -> rule.match(response))
.forEachOrdered(ResponseRule::performAction);