Contents > 9 Extending the Metrics and Rule Engine > 9.4 Boolean Functions > 9.4.1 Conception of a New Boolean Function

9.4.1 Conception of a New Boolean Function

Boolean functions occur in condition expressions (see Section 8.5 "Expression Terms") and yield Boolean (yes/no) values as results of conditions.

For example, let's assume we have a modeling process that defines a stereotype 'foobar' for classes. Classes of this stereotype must either contain operations, or contain attributes, or specialize some other class. We wish to define a rule that checks this constraint for 'foobar' classes.

Checking each condition individually is simple. We can use SDMetrics' standard class metrics NumOps, NumAttr, and DIT (depth of inheritance tree), and compare their values to 0. However, the condition expressions to assert that exactly one of the conditions holds is cumbersome:

  (NumOps!=0 and NumAttr=0 and DIT=0) or 
  (NumOps=0 and NumAttr!=0 and DIT=0) or 
  (NumOps=0 and NumAttr=0 and DIT!=0) 
The length of the condition expressions grows with the square of the number of individual conditions to check. The efficiency of evaluating this condition expressions is suboptimal, as each individual condition may be evaluated several times.

A Boolean function that calculates the "exclusive or" (XOR) for any number of conditions would be convenient in this situation. The condition expression could then be boiled down to
  xor(NumOps!=0, NumAttr!=0, DIT!=0)
With this new XOR function, we could define our rule as follows:
<rule name="FooBarCondition" domain="class">
<description>Classes with stereotype foobar must either define operations,
  attributes, or specialize another class.</description>
<violation condition=
  "('foobar' in StereotypeNames) and !xor(NumOps!=0, NumAttr!=0, DIT!=0)" />
</rule>
The condition term of the rule first checks if the class is of stereotype 'foobar' (we assume value set StereotypeNames was defined elsewhere to contain the names of the stereotypes of the class). If the stereotype condition holds, and the XOR function returns false, the condition term is true and the rule violation will be reported.