Chapter 8: Business Rules as Data
The chapter introduces data as a starting point for modern Java design, contrasting it with Java’s reputation for inheritance-heavy abstractions.
After this chapter you will be able to
- Modern Java design starting point. Explain why the chapter presents data as a starting point for design in modern Java rather than assuming inheritance-heavy patterns are necessary.
- Account routing challenge. Explain why assigning MegaCorp customer accounts to sales teams is difficult even though individual rules are simple, and describe the competing demands on the design.
- Purpose-built account data. Explain why the routing system models only the account information it needs instead of using the full Account entity, and describe the account representation introduced here.
- Disjoint rule sets. Explain when a collection of rules mapping accounts to Sales Org IDs counts as correct in this simplified model, including what can happen within one rule and what must not happen between rules.
- Domain and image invariant test. Describe how the section proposes checking the non-overlap constraints in Java using each rule’s domain and image.
- Direct Rule Implementation Limits. Explain why translating each rule into Java conditions becomes troublesome as the number of rules grows, even when each rule is simple.
- Interpreter Motivation For Rules. Explain why the section proposes an interpreter for business rules instead of simply generating more code or adopting a large rules framework.
- Operations represented as data. Explain how an equality check can be represented as data describing an operation to evaluate later, rather than only as code that performs the check immediately.
- Compound rules as data. Explain how AND and OR conditions become data types unified under a sealed Rule interface, allowing small rule expressions to form larger ones.
- Negation for excluding values. Explain why the algebra also needs negation: AND, OR, and the existing checks can express inclusive rules, but a rule such as a region not equaling EMEA must exclude a value.
- Composite rules from binary operations. Explain how compound actions such as containment or set inclusion can be expressed through repeated applications of simpler operations such as And and Or, using stream tooling because those operations are binary.
- Convenient composable rule interfaces. Describe why the section adds a more convenient interface instead of repeatedly defining rules such as eq(Country, ...), and explain how its new operations remain compatible with the rest of the algebra.
- Rule data interpretation. Explain how the interpreter gives rule data its Boolean meaning by pattern matching on the sealed rule types, translating each type to its corresponding operation, and looking up Account values through the Attribute enum.
- Explainable rule interpretation. Explain why the rules can remain unchanged while a new interpreter returns both a result and information about why the rule matched or did not match.
- Typed equality rule values. Explain why parameterizing Equals improves on String-based values but does not, by itself, prevent a rule from pairing an attribute with the wrong value type.
- Attribute and value type alignment. Describe how a generic Attr<A> wrapper around Attribute makes the attribute and equality value share a type when a rule is created.
- Typed account access evidence. Explain why Attr<A> must also carry a way to obtain an A from an Account, and how that changes value lookup in the interpreter.
- Interpreter implementation cost. State the approximate size and dependency cost of the type-safe interpreter built in this chapter.
- Requirements Over Completeness. Explain why the rule-handling code need not support every possible use case or become a framework.
- Rules as inspectable data. Explain why rules expressed as data are easier to inspect and transform programmatically than rules written directly as code.
- Documentation derived from rules. Explain how generating documentation directly from rule data addresses the risk of manually maintained documentation drifting from the rules.
- Comparison rules for account spend. Explain how GreaterThan and LessThan let rules compare data, such as assigning accounts with total spend above $5 million to a sales org, and still produce a report of why a rule matched or did not match.
- Generic comparison type workaround. Explain why Java needs help with the comparison during switch pattern matching and how moving the operation into a method with more type information addresses the issue.
- Modern Java’s Data Modeling Advantage. Explain why the section calls modern Java lean: records and pattern matching make it practical to model operations as data and build interpreters without the complex patterns and layers of indirection previously required.
What it builds on
- Capturing semantics in code (chapter 3) · Capturing domain meaning in code.
- Invariants, Properties, State, and an upside-down capital A (chapter 7) · Uses the idea of stating correctness as an invariant.
- Represent runtime decisions as compile time algebraic data types (chapter 5) · Earlier representation of decisions as data.
- The algebraic properties of binary operations (chapter 7) · The idea of binary operations and their algebraic properties.
Section by section
Introduction
The chapter introduces data as a starting point for modern Java design, contrasting it with Java’s reputation for inheritance-heavy abstractions.
- Modern Java design starting point: Explain why the chapter presents data as a starting point for design in modern Java rather than assuming inheritance-heavy patterns are necessary.
Why it matters: This frames why the chapter approaches business rules through data instead of assuming older Java design habits are required.
Key terms: records, pattern matching, data
8.1 Let’s start with an example
The section sets up an account-routing problem with numerous changing business rules and introduces a small, purpose-built data model for the accounts being routed.
- Account routing challenge: Explain why assigning MegaCorp customer accounts to sales teams is difficult even though individual rules are simple, and describe the competing demands on the design.
Why it matters: The scale and volatility of the rules explain why a quick implementation alone is not enough. - Purpose-built account data: Explain why the routing system models only the account information it needs instead of using the full Account entity, and describe the account representation introduced here.
Why it matters: A focused account model avoids carrying unrelated entity complexity into the routing problem.
Key terms: customer accounts, sales teams, rules, Account, Entity, plain data, domain types, enums, custom records
8.1.1 What does it mean to be correct?
Defines correctness for account-to-sales-organization rules as non-overlap, then shows how their inputs and outputs support a global invariant test.
- Disjoint rule sets: Explain when a collection of rules mapping accounts to Sales Org IDs counts as correct in this simplified model, including what can happen within one rule and what must not happen between rules.
Why it matters: These constraints give a precise meaning to correctness even when people invent or change the rules. - Domain and image invariant test: Describe how the section proposes checking the non-overlap constraints in Java using each rule’s domain and image.
Why it matters: Testing the shared property can reveal duplicate or conflicting rules without checking each rule combination by hand.
Key terms: Rule, Account, SalesOrgId, disjoint, non-overlapping sets, Image, domain, invariants, algebraic properties
8.2 Muscling through the rule implementation
This section shows why directly coding many business rules becomes hard to debug and maintain, and motivates an interpreter that can explain rule outcomes.
- Direct Rule Implementation Limits: Explain why translating each rule into Java conditions becomes troublesome as the number of rules grows, even when each rule is simple.
Why it matters: A rule’s result is less useful when the team cannot explain why it occurred. - Logging Versus Portable Rules: Describe why returning to if/else statements with extensive logging is not a satisfactory long-term solution.
Why it matters: Useful diagnostics alone do not solve the maintenance and rule-authoring problem. - Interpreter Motivation For Rules: Explain why the section proposes an interpreter for business rules instead of simply generating more code or adopting a large rules framework.
Why it matters: The proposed approach addresses the need to explain decisions rather than merely produce them.
Key terms: rules, if/else statements, Boolean expression, debug and monitor, runtime information, hard coded, portable, interpreter, rules engine, Domain Specific Languages (DSLs)
8.3 Capturing rules as plain data
The section represents an equality-check operation as data and narrows its attribute field to valid Account attributes.
- Operations represented as data: Explain how an equality check can be represented as data describing an operation to evaluate later, rather than only as code that performs the check immediately.
Why it matters: Representing the check as data makes it something the program can work with before evaluating it. - Restricted Account attribute names: Explain why the Equals type replaces a String attribute name with an enum of Account attributes, and identify the limitation that remains.
Why it matters: Restricting the attribute field prevents typos from naming Account attributes that do not exist.
Key terms: operations as data, equality check, Equals, Account, Enum, String
8.4 Building a simple Algebra
This section shows how to represent compound and excluding business rules as a small algebra of data, then make that algebra easier to use.
- Compound rules as data: Explain how AND and OR conditions become data types unified under a sealed Rule interface, allowing small rule expressions to form larger ones.
Why it matters: Representing operations as data lets simple rules combine into more expressive ones. - Negation for excluding values: Explain why the algebra also needs negation: AND, OR, and the existing checks can express inclusive rules, but a rule such as a region not equaling EMEA must exclude a value.
Why it matters: Exclusion is a common business-rule requirement that inclusive conditions alone do not express. - Fluent rule construction: Describe the two tweaks that make the rule data less verbose: static constructor methods remove new-expression boilerplate, and default methods on Rule support fluent and/or chaining.
Why it matters: A concise way to construct and combine rules makes the data representation practical to use.
Key terms: AND, OR, closed algebra, sealed interface, sum type, inclusive style rule, negates values, algebra, static constructor methods, default methods
8.4.1 Building better interfaces into the algebra
This section shows how to build concise, composable business rules by combining simple algebraic operations and adding a more convenient interface.
- Composite rules from binary operations: Explain how compound actions such as containment or set inclusion can be expressed through repeated applications of simpler operations such as And and Or, using stream tooling because those operations are binary.
Why it matters: It shows how a small set of operations can express more complex rules. - Convenient composable rule interfaces: Describe why the section adds a more convenient interface instead of repeatedly defining rules such as eq(Country, ...), and explain how its new operations remain compatible with the rest of the algebra.
Why it matters: A small algebra becomes more useful when rule authors can write clear expressions without repetitive boilerplate.
Key terms: compound actions, And, Or, binary operations, stream tooling, Rules, Algebra, eq(Country, ...), composite rules
8.5 Variation I: Deciding what data means
The section shows how to interpret business rules represented as data, then explains what that representation enables and what the basic interpreter cannot yet explain.
- Rule data interpretation: Explain how the interpreter gives rule data its Boolean meaning by pattern matching on the sealed rule types, translating each type to its corresponding operation, and looking up Account values through the Attribute enum.
Why it matters: A small interpreter lets the same rule data be evaluated even as the rules grow more complex. - Portability and evaluation limits: Describe what remains possible when complex rules are ordinary data, and state what the basic interpreter still cannot tell us about an evaluation.
Why it matters: Rule data can be reused beyond hand-written code, though a Boolean result alone does not provide an explanation.
Key terms: interpreter, sealed interface, pattern match, Attribute, Account, Equals, ordinary data, portable, serialize, debuggability
8.6 Variation II: A more powerful interpreter for the same data
This section shows how the same rule data can be interpreted to produce both a decision and an explanation, while noting a remaining type-safety limitation.
- Explainable rule interpretation: Explain why the rules can remain unchanged while a new interpreter returns both a result and information about why the rule matched or did not match.
Why it matters: Separating rules from their interpretation lets the program explain a decision without rewriting the rules. - Raw string type-safety limit: Describe why using raw strings in the rule algebra leaves some invalid rules undetected until runtime.
Why it matters: A more informative interpreter does not prevent mistakes in how rules are constructed.
Key terms: Booleans, Result type, interpreter, provenance information, denotations, raw strings, compile time safety, non-matching rule, runtime
8.7 Variation III: Adding Type Safety
The section makes equality rules type-safe by linking each account attribute to its value type, then adapts the interpreter while keeping the rules as data.
- Typed equality rule values: Explain why parameterizing Equals improves on String-based values but does not, by itself, prevent a rule from pairing an attribute with the wrong value type.
Why it matters: Using a real domain type helps only if the rule also requires the right type for its attribute. - Attribute and value type alignment: Describe how a generic Attr<A> wrapper around Attribute makes the attribute and equality value share a type when a rule is created.
Why it matters: The wrapper lets Java reject mismatched rules where they are created. - Typed account access evidence: Explain why Attr<A> must also carry a way to obtain an A from an Account, and how that changes value lookup in the interpreter.
Why it matters: A typed rule must also give the interpreter a sound way to read the value it names. - Generic interpretation remains data: Describe how the interpreter matches the generic rule data without specifying concrete types, and why the added type information does not stop the rules from being data.
Why it matters: Type safety can help programmers without giving up the flexibility of rules represented as data.
Key terms: Equals, String, Account, Segment, Attr<A>, Attribute, Region, interpreter, evidence, wildcard
8.8 What did this cost us?
This section shows that the hand-built, type-safe interpreter takes about 60 lines of pure Java and needs no dependencies.
- Interpreter implementation cost: State the approximate size and dependency cost of the type-safe interpreter built in this chapter.
Why it matters: It puts a concrete cost on building this interpreter without an external library.
Key terms: interpreter, type safe, dependencies, pure Java
8.9 But It doesn’t do everything!
This section argues that representing business rules as data is useful without turning the resulting code into a general-purpose interpreter or framework.
- Requirements Over Completeness: Explain why the rule-handling code need not support every possible use case or become a framework.
Why it matters: Keeping the requirements in view helps you avoid adding tools and features just in case. - Data Description and Handling: Describe the recurring pattern the author sees when core domain ideas are modeled as data.
Why it matters: Recognizing this pattern lets you use it where it fits without making it a universal solution.
Key terms: interpreter, DSL, business code, requirements, model with data, mini-interpreters, core ideas in your domain
8.10 Data is flexible in a way that code isn’t
The section shows how representing business rules as data makes it possible to generate documentation and visualizations from the rules themselves, rather than maintaining separate descriptions by hand.
- Rules as inspectable data: Explain why rules expressed as data are easier to inspect and transform programmatically than rules written directly as code.
Why it matters: This difference determines whether new views of the rules can be generated from the rules themselves. - Documentation derived from rules: Explain how generating documentation directly from rule data addresses the risk of manually maintained documentation drifting from the rules.
Why it matters: Stakeholders can review documentation that reflects the rules the system actually uses. - Rule tree visualization: Describe how the same rule data can be transformed into a visual view for documentation.
Why it matters: A visual presentation can make rule documentation more useful to its audience than a spartan text rendering.
Key terms: rules as code, rules as data, documentation pipeline, Tree, GraphViz, nodes and edges
8.11 Extending the algebra:
This section extends the business-rule algebra to compare account data and explains the Java type issue involved in interpreting those comparisons.
- Comparison rules for account spend: Explain how GreaterThan and LessThan let rules compare data, such as assigning accounts with total spend above $5 million to a sales org, and still produce a report of why a rule matched or did not match.
Why it matters: Threshold-based territory decisions can be expressed as rules over account data. - Generic comparison type workaround: Explain why Java needs help with the comparison during switch pattern matching and how moving the operation into a method with more type information addresses the issue.
Why it matters: It explains the extra Java code needed to make the new comparison rules work.
Key terms: GreaterThan, LessThan, algebra, interpreter, wildcards, generic types, switch expression
8.12 Wrapping up
The section concludes that modern Java makes modeling operations as data and interpreting them less costly than older pattern-heavy approaches.
- Modern Java’s Data Modeling Advantage: Explain why the section calls modern Java lean: records and pattern matching make it practical to model operations as data and build interpreters without the complex patterns and layers of indirection previously required.
Why it matters: It captures why the chapter presents rules-as-data as a practical approach in modern Java.
Key terms: operations as data, interpreters, records, pattern matching
8.13 Summary
Concepts explained in this chapter
- dataData is information represented independently of the behaviors that operate on it.
- business ruleA business rule is a domain constraint or policy that determines valid actions, states, or outcomes.
- algebraic operationAn algebraic operation is a rule for combining elements of specified sets to produce an element of a specified result set.
- EqualsA book-specific rule model representing equality between an attribute and a value, with the value type parameterized by the attribute.
- provenanceProvenance is information describing the origin and sequence of steps that produced a result or movement of data.
- pipelineA pipeline is a sequence of processing stages in which data is passed from one stage to the next.
- data typeA data type is a classification of data that determines its representation, permitted values, and valid operations.
- operationAn operation is a rule that combines or transforms values from a specified set to produce a value.
- data modelA database model is a structured representation of data entities, attributes, and relationships as persisted by a database.
- accuracyCorrectness is the property that an implementation produces the behavior and results specified by its intended semantics and requirements.
- invariantAn invariant is a condition that must remain true across the valid states of a data structure or computation.
- partitionA partition divides a set into subsets that are collectively exhaustive and pairwise disjoint.
- attributeAn attribute is a named component of a data representation that describes one property of an entity or value.
- enumAn enum is a Java type construct that defines a fixed set of named constant values.
- factoryA factory function is a function that constructs and returns an instance or structured test datum through a defined parameter interface.
- fluent interfaceFluent chaining is an API style in which successive operations are linked through return values to form an expression-like sequence.
- sealed typeA sealed Java type restricts which classes or interfaces may directly extend or implement it.
- union typeA sum type is a type formed by combining alternative types with OR semantics so that a value belongs to one of several permitted variants.
- software testingTesting is the practice of executing checks that assess whether software behaves according to specified expectations.
- type safetyType safety is the property that a programming language or program prevents operations from being applied to values of incompatible types.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
