Contents > 9 Extending the Metrics and Rule Engine > 9.4 Boolean Functions > 9.4.2 Implementation of the Boolean Function
9.4.2 Implementation of the Boolean Function
The following listing shows the complete implementation of the XOR function outlined
in the previous section. The function successively evaluates the condition expressions
passed as arguments to the XOR function. The result of the function is true
if exactly one of the individual condition expressions is true
:
package com.acme;
import com.sdmetrics.math.ExpressionNode;
import com.sdmetrics.metrics.BooleanOperation;
import com.sdmetrics.metrics.SDMetricsException;
import com.sdmetrics.metrics.Variables;
import com.sdmetrics.model.ModelElement;
01 public class BooleanOperationXOR extends BooleanOperation {
@Override
02 public boolean calculateValue(ModelElement element,
03 ExpressionNode node,
04 Variables vars)
05 throws SDMetricsException {
06 int trueConditions = 0;
07 int index = 0;
08 while (index < node.getOperandCount() && trueConditions <= 1) {
09 if (evalBooleanExpression(element, node.getOperand(index), vars)) {
10 trueConditions++;
}
11 index++;
}
12 return trueConditions == 1;
}
}
Let's go through the salient points of this implementation line by line:
- 01: Boolean function classes must have public visibility, a default or no-argument
constructor, and extend the abstract class com.sdmetrics.metrics.BooleanOperation.
- 02: The base class defines the abstract method calculateValue which we must override.
Parameter
element
is the model element for which to evaluate the function.
- 03: Parameter
node
contains the operator tree for the function call.
The operands of the node represent the arguments passed into the function.
- 04: Parameter
vars
contains the values of the variables defined for the
evaluation of the arguments to the function.
- 08: The XOR function in this example has an arbitrary number of arguments.
Method getOperandCount() obtains the actual number of arguments passed to the
function. Other functions may have a fixed number of arguments, in which case
we would not need to determine the argument count.
- 09: We use method evalBooleanExpression provided by the base class to
evaluate the condition expressions that are passed as arguments to the XOR function,
one by one.
Method node.getOperand(index) accesses the arguments to the XOR function
by their index. The first argument has index 0, the second argument has index 1, and so on.
- 12: Boolean functions must return a value of type
boolean
.
Prev |
Up |
Next |
Section 9.4.1 "Conception of a New Boolean Function" | Contents | Section 9.4.3 "Using the New Boolean Function" |