1

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 Translator {
    public void maybeTranslate() {
        if (!condition1 || !condition2 || !condition3) {
            return;
        }

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

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 Translator {
    private Rule[] rules;

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

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

        translate();
    }
}

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 maybeTranslate 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 Translator would be instantiated on different fragments.


UPDATE: Some changes from my original question.

This Translator will be used on multiple screens. There is only one screen active at a time, and each screen can have a different set of rules.

Instead of making a rule take in a parameter and act differently, I created multiple screen-dependent rules (ScreenOneRule, ScreenTwoRule, etc.).

Now I would use the class like this:

public class ScreenOne {
    Translator translator;

    public Screen(Translator translator) { ... }

    public void onSomeEvent() { translator.maybeTranslate(); }
}

and I would create the set of rules for ScreenOne in my IoC configuration (this is an attempt at pseudo code):

Rule[] screenOneRules = new Rule[] { SharedRule1, SharedRule2, ScreenOneRule1 }
ScreenOne screenOne = new Screen(new Translator(screenOneRules))

This solves my problem, though I feel like the design is not perfect. What if I get a rule later on that depends on a value only known after the screen has been instantiated? For example, say a rule needs to know the (x,y) coordinates of where the user tapped on screen to trigger onSomeEvent. I have a feeling ScreenOne would need to construct the rules itself in onSomeEvent. I think this is coming back to my original question.

In that case, I would want to have the instantiation of rules somewhere else. Is the solution to have a factory like this?

public class RuleFactory {
    public Rule[] getRulesForScreenOne(int x, int y, String anotherParameter) {
        return new Rule[] { new SharedRule1(x, y), new SharedRule2(anotherParameter) };
    }
}

public void onSomeEvent() { 
    Rule[] rules = RuleFactory.getRulesForScreenOne(x, y, str);
    translator.maybeTranslate(rules);
}

At that point, Translator would not receive rules in its constructor. I can't put my finger on it, but I feel like the factory implementation isn't right. Something about that method name.

  • Please tell more about this new String parameter. Whose responsibility is to create such value? – Basilevs Mar 28 '15 at 12:35
  • What information other rules require and where is it stored? – Basilevs Mar 28 '15 at 16:21
  • The actual scenario is something like: Screens A & B both reference MyClass and call its maybeTriggerEvent when some user generated event is raised. One of the rules cares about knowing which screen the event was raised from. I'd say it's the screen's responsibility to create that String parameter. – siger Mar 28 '15 at 19:16
  • Other rules depend on: system time, values stored in persistent storage. Rules get those dependencies in their constructor when I build my application graph. – siger Mar 28 '15 at 19:19
  • Right now I'm thinking of having screen-dependent rules, such as ScreenATimeRule, ScreenBTimeRule, and instantiate two versions of MyClass; each injected with a different set of Rule[]. Screens become responsible for using the right MyClass and there is no need to pass a parameter. – siger Mar 28 '15 at 19:21
1

I guess your Rule class is an example of specification or command pattern. Definitely different rules will need different types of information to do its work, but if it were me, I would not pass those information during method invocation, I would use constructor instead. The information that is different from one rule to another is the implementation detail of that rule, the invoker of the rule should not need to know about that, the invoker just needs to know the public interface of the rule. The knowledge to construct the rule should be put on client or another class.

The client of MyClass is the one that pass array of rules to MyClass, so it can be the one who create the rule, or it can delegate to a factory class to create the rule, or if you use dependency injection, you can rely on IoC to inject the list of rules for you. Either case, the data that is different between each rule class should be passed in Rule at that time:

//Client
Rule[] rules = new Rule[2];
rules[0] = new AnExampleRule("some context information");
rules[1] = new AnotherRule(12);

MyClass myClass = new MyClass(rules);
0

In a similar situation I am using a state machine. The fact that your rule needs the source of the event tells me that your rule must consider the context of the event, i.e. the state your are in. In my suggested state machine scenario your model would be like this:

  • You represent the "world" in your application by defining the possible states with relevant quantifiable variables. (e.g. screen name is 'xy', or userLoggedIn == true, and so on).
  • You add a generic function that checks which state you are in.
  • You register possible transitions for every state (possible steps/events that will bring your application into another state).
  • You create the logic (a heuristic function) to prioritize available transitions so your program code will choose one of the possible events.

I know, it is a short answer compared to the size of the topic, but I think you can go on with these keywords and learn more with the help of google.

Hope this helps.

  • -1 Global state and transitions seem to be too far fetched. The question was about events. – Basilevs Mar 28 '15 at 12:33
  • @Basilevs your comment is subjective. It seems far fetched to you. Why? If you read about state machines, you'll have the ability to implent the right event handler. This is how I learnt it. – Mark Mar 28 '15 at 14:08
  • You are proposing new Rule to subscribe for parameter value updates and use its persisted value to implement internal predicate. Am I right? – Basilevs Mar 28 '15 at 15:02
  • OK, now I understand. Your question is on a more detailed level than my answer, so let's dig down. The key new aspect of my answer is the representation of state or context. So what is missing from the model in the question, is not another rule, rather the notion of context. The question mentioned several rules and a complex scenario so I would leave it to the owner of the question to decide about the implementation. I think a simple implemented form of context would be to pass the source object to the rules. In more complex cases you need state objects and heuristics also. – Mark Mar 28 '15 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.