jeudi 26 mars 2015

Pattern for validating rules having different signatures


I have a class in charge of responding to an input event and maybe triggering another event. To decide, it has several rules to check.


I'm trying to get away from a class looking like this:



public class MyClass {
public void maybeTriggerEvent() {
if (!condition1 || !condition2) {
return;
}

// All rules have passed
triggerEvent();
}
}


I'd like this class to know that it has rules to pass, but not know about the implementations of rules. My attempt was to transform it like so:



public class MyClass {
private Rule[] rules;

public MyClass(Rule[] rules) { this.rules = rules; }

public void maybeTriggerEvent() {
for (Rule rule : rules) {
if (!rule.passes()) {
return;
}
}

triggerEvent();
}
}


where a Rule has this interface:



public interface Rule {
boolean passes();
}


Here comes my problem: I now have a new rule that takes in a parameter. Its passes method would require a String parameter. Is my foundation wrong with this new requirement? I don't see how I can adapt this pattern to accommodate rules having various parameters.


This parameter would indicate the source of the input event. I can modify maybeTriggerEvent to receive this value from whoever calls it, and change the Rule interface to be boolean passes(String str). Only now, the majority of my rules are getting a parameter they don't care about.


This is in the context of an Android app, where MyClass would be instantiated on different fragments.





Aucun commentaire:

Enregistrer un commentaire