Equals models an equality operation as plain data: an attribute and the value it should match. Representing operations this way lets rules be stored, composed, and evaluated later rather than hard-coding every decision. section 8.3
The model becomes safer through several focused refinements:
- Replace free-form attribute names with an Attribute enum so misspelled or nonexistent fields cannot enter the rule model. section 8.3
- Parameterize Equals so its value is no longer restricted to String and can use domain types such as CountryCode, Region, or SalesChannel. section 8.7
- Wrap the attribute in Attr<A> so the selected attribute and its value type must agree; a region accepts Region values, not CountryCode values. section 8.7
- Store a typed Account getter in Attr<A>, giving Java concrete evidence for retrieving and comparing the selected value. section 8.7
A type-safe equality rule
A rule can pair a channel with SalesChannel.Reseller or a region with Region.EMEA. Pairing the channel with Region.EMEA is rejected by the type system. Interpretation applies the attribute getter to an Account, compares the result with the expected value, and produces both a boolean result and formatted evidence such as REGION=EMEA. section 8.7 section 8.7
Listing 8.43 Type safety! Hooray!
static Attr<SalesChannel> channel = new Attr<>(Attribute.CHANNEL); #A static Attr<Region> region = new Attr<>(Attribute.REGION); #A // etc. new Equals<>(channel, SalesChannel.Reseller); #B new Equals<> (region, Region.EMEA); #B new Equals<>(channel, Region.EMEA) // Nope! #C
Shows the final attribute-value pairing and the invalid construction that the type system rejects. section 8.7
Listing 8.49 Finish up the equality implementation
static Result interpret(Account account, Rule rule) {
return switch (rule) {
case Equals(var attr, var value) -> {
var found = attr.getter().apply(account); #A
boolean result = found.equals(value); #B
yield new Result(result,
format("%s=%s", attr.attribute(), value), #C
format("%s=%s", attr.attribute(), found)); #C
}Shows the completed interpretation path from a generic equality rule to lookup, comparison, and diagnostic output. section 8.7
