Rule inheritance

One last important aspect of rule creation is the possibility of having a rule hierarchy. Just like classes, rules allow inheritance between them. If rule B inherits rule A, it will be the same as having all the conditions in rule A at the beginning of the conditions of rule B. The following table shows two rules using inheritance and their equivalent without it:

rule "A"
whens: String(this == "A")
thenSystem.out.println(s);
end

rule "B" extends "A"
when
  i: Integer(intValue > 2)
then  System.out.println(i);
end

rule "A"
whens: String(this == "A")
thenSystem.out.println(s);
end

rule "B"
whens: String(this == "A")i: Integer(intValue > 2)
thenSystem.out.println(i);
end

This can be a good strategy to manage rules that have repetitive conditions but still change structure. However, you need to be careful when deciding to use rule inheritance. Inheriting from another rule means that your sub-classed rule will not be independent; people reading your rule will need to refer to the parent rule to fully understand the behavior of your rule. Use this feature with caution.

Conditional named consequences

Rule inheritance allows us to avoid rewriting conditions as separate rules by extending an existing rule. Another interesting feature that allows us to avoid rewriting conditions is the possibility of using conditionally named consequences. They are basically extra then clauses marked by an identifier to make one rule behave as several. The same identifier has to be used in the rule condition with the go keyword to identify when you should go to that specific consequence. For example, if we wanted to write the two rules that we saw in the rule inheritance subsection as a single rule, we could do it in the following way:

rule "A and B combined"
    whens: String(this == "A")
        do[aCase]
        i: Integer(intValue > 2)
    thenSystem.out.println(i);
    then[aCase]
        System.out.println(s);
end

As you can see in the previous rule, we can use the do keyword to mark a point in the conditions where we can go to a specific consequence. If all the conditions in the rule are true, both consequences would execute, similar to the case that we would see if we defined two different rules.

Same as with rule inheritance, we must be very careful of using this feature. It can save us a lot of rewriting, but it can also provoke one rule to become very cumbersome to read in the long run. It is usually a good workaround when required to quickly update an existing rule, but not something you want to abuse so much that the rule becomes hard to read. Simplicity is key to making rules easy to understand and modify.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.108.185