|
| 1 | +--- |
| 2 | +title: "Rule Engine Pattern in Java: Replacing Tangled Conditionals with Composable Rules" |
| 3 | +shortTitle: Rule Engine |
| 4 | +description: "Learn the Rule Engine design pattern in Java. Encapsulate each business rule as an independent object and let an engine evaluate and execute them against a shared context, replacing large nested if/else blocks with small, testable, composable rules." |
| 5 | +category: Behavioral |
| 6 | +language: en |
| 7 | +tag: |
| 8 | + - Business |
| 9 | + - Decoupling |
| 10 | + - Domain |
| 11 | + - Encapsulation |
| 12 | + - Extensibility |
| 13 | +--- |
| 14 | + |
| 15 | +## Intent of Rule Engine Design Pattern |
| 16 | + |
| 17 | +Encapsulate each business rule as an independent, self-contained object and let an engine evaluate and execute a collection of those rules against a shared context, so that decision logic can grow and change without rewriting a large nested conditional block. |
| 18 | + |
| 19 | +## Detailed Explanation of Rule Engine Pattern with Real-World Examples |
| 20 | + |
| 21 | +Real-world example |
| 22 | + |
| 23 | +> A bank decides whether to approve a loan by checking several independent criteria: the applicant must be old enough, earn enough, and have a good enough credit score. Instead of hard-coding one enormous condition, the bank keeps each criterion as a separate policy on a checklist. A clerk walks the whole checklist for every application, ticks off the criteria that pass, and writes down the ones that fail. Adding a new criterion means adding a line to the checklist, not rewriting the whole approval procedure. |
| 24 | +
|
| 25 | +In plain words |
| 26 | + |
| 27 | +> The Rule Engine pattern turns each branch of a giant `if/else` into its own object and hands a collection of them to an engine that runs them all against the same input, collecting which passed and which failed. |
| 28 | +
|
| 29 | +## Programmatic Example of Rule Engine Pattern in Java |
| 30 | + |
| 31 | +Each rule separates the **decision** (`evaluate`) from the **action** (`execute`). `evaluate` reports whether a rule's condition holds; `execute` performs the side effect associated with a satisfied rule. |
| 32 | + |
| 33 | +```java |
| 34 | +public interface Rule<T> { |
| 35 | + |
| 36 | + String name(); |
| 37 | + |
| 38 | + boolean evaluate(T context); |
| 39 | + |
| 40 | + void execute(T context); |
| 41 | +} |
| 42 | +``` |
| 43 | + |
| 44 | +The context is an immutable value object that carries the data the rules inspect. |
| 45 | + |
| 46 | +```java |
| 47 | +public record LoanApplication( |
| 48 | + int age, double monthlyIncome, double loanAmount, int creditScore) {} |
| 49 | +``` |
| 50 | + |
| 51 | +Concrete rules encapsulate one criterion each. New criteria are added by writing new classes — the engine never changes. |
| 52 | + |
| 53 | +```java |
| 54 | +public class MinimumAgeRule implements Rule<LoanApplication> { |
| 55 | + |
| 56 | + private final int minimumAge; |
| 57 | + |
| 58 | + public MinimumAgeRule(int minimumAge) { |
| 59 | + this.minimumAge = minimumAge; |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + public String name() { |
| 64 | + return "MinimumAgeRule"; |
| 65 | + } |
| 66 | + |
| 67 | + @Override |
| 68 | + public boolean evaluate(LoanApplication context) { |
| 69 | + return context.age() >= minimumAge; |
| 70 | + } |
| 71 | + |
| 72 | + @Override |
| 73 | + public void execute(LoanApplication context) { |
| 74 | + LOGGER.info("Applicant age {} meets the minimum age of {}.", context.age(), minimumAge); |
| 75 | + } |
| 76 | +} |
| 77 | +``` |
| 78 | + |
| 79 | +The engine holds a defensively copied, immutable list of rules. It evaluates every rule in insertion order, executes the ones that pass, and reports the combined outcome. It never stops at the first failure, so a single run reports *all* the reasons an application was rejected. |
| 80 | + |
| 81 | +```java |
| 82 | +public class RuleEngine<T> { |
| 83 | + |
| 84 | + private final List<Rule<T>> rules; |
| 85 | + |
| 86 | + public RuleEngine(List<Rule<T>> rules) { |
| 87 | + this.rules = List.copyOf(rules); |
| 88 | + } |
| 89 | + |
| 90 | + public RuleEngineResult run(T context) { |
| 91 | + Objects.requireNonNull(context, "context must not be null"); |
| 92 | + List<String> passed = new ArrayList<>(); |
| 93 | + List<String> failed = new ArrayList<>(); |
| 94 | + for (Rule<T> rule : rules) { |
| 95 | + if (rule.evaluate(context)) { |
| 96 | + rule.execute(context); |
| 97 | + passed.add(rule.name()); |
| 98 | + } else { |
| 99 | + failed.add(rule.name()); |
| 100 | + } |
| 101 | + } |
| 102 | + return new RuleEngineResult(failed.isEmpty(), passed, failed); |
| 103 | + } |
| 104 | +} |
| 105 | +``` |
| 106 | + |
| 107 | +The result is an immutable value object describing the run. |
| 108 | + |
| 109 | +```java |
| 110 | +public record RuleEngineResult( |
| 111 | + boolean approved, List<String> passedRules, List<String> failedRules) { |
| 112 | + |
| 113 | + public RuleEngineResult { |
| 114 | + passedRules = List.copyOf(passedRules); |
| 115 | + failedRules = List.copyOf(failedRules); |
| 116 | + } |
| 117 | +} |
| 118 | +``` |
| 119 | + |
| 120 | +Putting it together, the `App` builds an engine and runs two applications through it. |
| 121 | + |
| 122 | +```java |
| 123 | +var engine = |
| 124 | + new RuleEngine<>( |
| 125 | + List.of( |
| 126 | + new MinimumAgeRule(18), |
| 127 | + new MinimumIncomeRule(2000.0), |
| 128 | + new CreditScoreRule(650))); |
| 129 | + |
| 130 | +engine.run(new LoanApplication(30, 3500.0, 15000.0, 720)); // approved |
| 131 | +engine.run(new LoanApplication(17, 1500.0, 15000.0, 720)); // rejected: age and income |
| 132 | +``` |
| 133 | + |
| 134 | +Program output: |
| 135 | + |
| 136 | +``` |
| 137 | +Applicant age 30 meets the minimum age of 18. |
| 138 | +Applicant income 3500.0 meets the minimum income of 2000.0. |
| 139 | +Applicant credit score 720 meets the minimum score of 650. |
| 140 | +Loan approved. Passed rules: [MinimumAgeRule, MinimumIncomeRule, CreditScoreRule] |
| 141 | +Applicant credit score 720 meets the minimum score of 650. |
| 142 | +Loan rejected. Failed rules: [MinimumAgeRule, MinimumIncomeRule] |
| 143 | +``` |
| 144 | + |
| 145 | +### Behavioral decisions |
| 146 | + |
| 147 | +The example commits to the following semantics, each covered by tests: |
| 148 | + |
| 149 | +* `evaluate` returning `true` means the rule **passes** (its condition is satisfied); a passing rule then has its `execute` action run. |
| 150 | +* The engine evaluates **every** rule; it does not stop after the first failure, so all rejection reasons are reported. |
| 151 | +* Outcomes are reported as an immutable `RuleEngineResult` carrying the overall `approved` flag plus the names of the passed and failed rules. |
| 152 | +* Rules execute in **insertion order**. |
| 153 | +* A `null` context passed to `run` throws `NullPointerException`; a `null` rule collection or a `null` rule element is rejected on construction. |
| 154 | +* An engine with **no rules** approves vacuously (nothing failed). |
| 155 | + |
| 156 | +## Class diagram |
| 157 | + |
| 158 | +See [rule-engine.urm.puml](./etc/rule-engine.urm.puml) for the PlantUML class diagram. |
| 159 | + |
| 160 | +## When to Use the Rule Engine Pattern in Java |
| 161 | + |
| 162 | +* Decision logic is a growing set of independent conditions that would otherwise become a large, hard-to-read nested `if/else`. |
| 163 | +* Rules must be added, removed, or reordered without touching the code that coordinates them. |
| 164 | +* You need to report *all* failing conditions, not just the first one. |
| 165 | +* Business rules deserve to be unit tested in isolation. |
| 166 | + |
| 167 | +## Real-World Applications of Rule Engine Pattern in Java |
| 168 | + |
| 169 | +* Loan, insurance, and credit approval workflows. |
| 170 | +* Validation frameworks such as Bean Validation, where each constraint is an independent rule. |
| 171 | +* Fraud detection and risk scoring, where many independent checks contribute to one decision. |
| 172 | +* Pricing, discount, and promotion eligibility engines. |
| 173 | + |
| 174 | +## Benefits and Trade-offs of Rule Engine Pattern |
| 175 | + |
| 176 | +Benefits |
| 177 | + |
| 178 | +* Encapsulation: each rule owns one criterion. |
| 179 | +* Extensibility: new rules are new classes; the engine is closed for modification. |
| 180 | +* Testability: rules and the engine can be tested independently. |
| 181 | +* Transparency: the result lists every passed and failed rule. |
| 182 | + |
| 183 | +Trade-offs |
| 184 | + |
| 185 | +* Debugging a decision means tracing several small objects instead of reading one block. |
| 186 | +* Rule ordering and conflicts must be managed deliberately when rules are not independent. |
| 187 | +* Over-abstracting trivial logic into a rule engine adds indirection that a simple `if` would not. |
| 188 | + |
| 189 | +## Related Java Design Patterns |
| 190 | + |
| 191 | +* [Specification](../specification): combines boolean criteria that an object must satisfy; a Rule Engine orchestrates and executes such criteria. |
| 192 | +* [Chain of Responsibility](../chain-of-responsibility): passes a request along handlers; a Rule Engine instead runs every rule against one context. |
| 193 | +* [Strategy](../strategy): each rule is effectively a pluggable strategy for one decision. |
| 194 | +* [Command](../command): a rule's `execute` action resembles an encapsulated command. |
| 195 | + |
| 196 | +## References and Credits |
| 197 | + |
| 198 | +* [Patterns of Enterprise Application Architecture](https://www.amazon.com/gp/product/0321127420) (Martin Fowler) |
| 199 | +* [Should I use a Rules Engine? (Martin Fowler)](https://martinfowler.com/bliki/RulesEngine.html) |
0 commit comments