Learn how to build a high-performance, zero-dependency, type-safe rule engine in Java using modern language features. You will model business logic as compile-time verified Abstract Syntax Trees using sealed hierarchies, records, and exhaustive switch expressions. By the end of this tutorial, you will eliminate runtime casting exceptions and dynamic reflection overhead from your domain logic.
- Model domain rules cleanly using modern Java algebraic data types.
- Evaluate Boolean rule trees with exhaustive pattern matching java switch expressions.
- Deconstruct nested domain payloads cleanly using java record patterns switch expression syntax.
- Build a production-ready discount and fraud risk rule engine without dynamic string evaluators.
Introduction
Legacy rule engine frameworks suffer from a silent killer: string-based expression languages that compile fine, run smoothly in development, and crash catastrophically in production when a developer renames a field. Mastering java sealed interface pattern matching allows you to replace those brittle runtime evaluators with compiler-verified domain logic.
As modern services standardize on current Java LTS baselines, engineering teams are abandoning heavy reflection-based tools like Drools or SpEL. By leveraging modern Java algebraic data types, developers can express business rules directly inside typed Java code. This transition eliminates entire categories of runtime casting exceptions, null pointer bugs, and unexpected side effects.
In this guide, we will build a zero-dependency type safe rule engine java developers can drop straight into production. You will learn how to structure predicates as pure data, evaluate them using exhaustive pattern matching for switch, and deconstruct domain models cleanly without standard boilerplates.
Traditional engines parse raw strings at runtime, creating performance bottlenecks and untyped dynamic contexts. Structuring rules as typed abstract syntax trees (ASTs) gives you instant auto-completion, refactoring safety, and static analytical validation.
Architecting the Rule Engine AST
Before writing code, we must clarify what a rule engine actually is. At its core, a rule engine evaluates an input payload against a tree of conditional predicates and returns a deterministic result. We can model every complex condition as an Abstract Syntax Tree (AST) composed of logical operators and field comparisons.
Instead of creating traditional mutable class hierarchies, we will represent our AST nodes using domain modeling with java records combined with sealed interfaces. This architecture forces every rule node to be an immutable value object, making rules easy to store, compose, test, and pass across thread boundaries.
// Project AST Layout Architecture
org.syuthd.rules/
├── Rule.java // Sealed parent interface for all nodes
├── EvaluationContext.java// Wrapped domain payload context
├── Evaluator.java // Core pattern matching engine
└── rules/
├── And.java // Logical AND composite
├── Or.java // Logical OR composite
├── Not.java // Logical NOT predicate
└── Equals.java // Terminal comparison leaf nodeThe code layout above outlines the design of our engine. Logical nodes like And, Or, and Not act as branch nodes that contain other rules. Comparison nodes like Equals act as leaf nodes that perform actual property checks against incoming data contexts.
Milestone 1: Domain Modeling with Java Records and Sealed Interfaces
We begin by defining the primary contracts of our rule system. The root element is a Rule<T> sealed interface that permits explicit logical operations and leaf node checks. By sealing this interface, we restrict implementation to known record types, allowing the Java compiler to guarantee exhaustive switch coverage.
package org.syuthd.rules;
import java.util.List;
import java.util.function.Function;
// Sealed interface defining all allowable rule types
public sealed interface Rule<T>
permits Rule.And, Rule.Or, Rule.Not, Rule.Equals, Rule.GreaterThan {
record And<T>(List<Rule<T>> rules) implements Rule<T> {}
record Or<T>(List<Rule<T>> rules) implements Rule<T> {}
record Not<T>(Rule<T> rule) implements Rule<T> {}
record Equals<T, V>(Function<T, V> extractor, V expectedValue) implements Rule<T> {}
record GreaterThan<T, V extends Comparable<V>>(Function<T, V> extractor, V threshold) implements Rule<T> {}
}In this design, leaf nodes like Equals accept a type-safe property extractor function Function<T, V> instead of a raw property name string. This technique binds field selection directly to the strong types of your target domain objects, eliminating runtime reflection entirely.
Every implementation of Rule<T> is expressed as an immutable record. Records eliminate boilerplate getters, constructors, equals(), and hashCode() routines while serving as the foundational building blocks for modern algebraic data types.
Using standard functional interfaces like Function<T, V> inside leaf records preserves full refactoring capability in your IDE. Renaming a target getter method renames the extractor reference across all defined rules instantly.
Milestone 2: Building the Exhaustive Evaluator Engine
With our tree structure fully modeled as immutable types, we can construct the evaluator. The evaluator navigates the AST recursively, using pattern matching for switch to deconstruct rules and resolve their boolean output against an incoming target object.
package org.syuthd.rules;
public final class RuleEvaluator {
// Main evaluation pipeline
public static <T> boolean evaluate(Rule<T> rule, T target) {
return switch (rule) {
case Rule.And<T>(var subRules) ->
subRules.stream().allMatch(r -> evaluate(r, target));
case Rule.Or<T>(var subRules) ->
subRules.stream().anyMatch(r -> evaluate(r, target));
case Rule.Not<T>(var subRule) ->
!evaluate(subRule, target);
case Rule.Equals(var extractor, var expected) -> {
var actual = extractor.apply(target);
yield actual != null && actual.equals(expected);
}
case Rule.GreaterThan(var extractor, var threshold) -> {
var actual = extractor.apply(target);
yield actual != null && actual.compareTo(threshold) > 0;
}
};
}
}Notice the complete absence of a default clause in the switch expression. Because Rule<T> is sealed, the Java compiler verifies that all permitted subtypes are explicitly covered in the switch arms.
If another developer adds a new record type to Rule<T> in the future, the evaluator will immediately fail to compile. This forces developers to handle new rule logic everywhere it matters, completely eliminating unhandled edge case bugs.
Avoid adding a default: throw new IllegalArgumentException() clause to switch expressions operating on sealed interfaces. Doing so bypasses the compiler's exhaustive checking, forfeiting your static type safety guarantees.
Milestone 3: Leveraging Record Deconstruction for Complex Contexts
Simple property checks are fine, but enterprise applications often require matching deeply nested records directly. Modern Java allows us to extract variables straight out of multi-layer record trees during switch branch selection.
Suppose our application works with explicit payment payloads containing buyer profiles and location data. We can write specialized rules that match nested record patterns instantly inside switch statements.
package org.syuthd.rules.domain;
// Domain records representing an incoming transaction payload
public record Address(String countryCode, String city) {}
public record Customer(String id, int riskScore, Address address) {}
public record OrderPayload(String orderId, double amount, Customer customer) {}We can now construct specialized sub-evaluators that deconstruct OrderPayload records directly, executing logic based on internal values without manually writing deep null checks or long chained getter calls.
package org.syuthd.rules;
import org.syuthd.rules.domain.*;
public class RiskAnalyzer {
// Advanced rule evaluation using nested record patterns
public static String classifyRisk(OrderPayload payload) {
return switch (payload) {
// Match high risk score regardless of country
case OrderPayload(var id, var amount, Customer(var cId, int score, var addr))
when score > 80 -> "REJECT_HIGH_RISK_SCORE";
// Match high-value transactions originating from designated regions
case OrderPayload(var id, double amount, Customer(var cId, var score, Address(String country, var city)))
when amount > 10_000.00 && "RISK_ZONE_A".equals(country) -> "FLAG_MANUAL_REVIEW";
// Default safe categorization
case OrderPayload overall -> "AUTO_APPROVE";
};
}
}The record pattern OrderPayload(var id, double amount, Customer(var cId, int score, Address(String country, var city))) unpacks three levels of nested data structures in a single concise line.
Using guard conditions (the when clause) allows us to apply precise boolean logic alongside variable extraction. If a guard evaluates to false, execution falls through cleanly to subsequent patterns.
Real-World Example: E-Commerce Fraud & Discount Engine
To demonstrate the real-world value of this approach, let's look at an automated checkout processing engine. We will build a service that determines whether an e-commerce order receives a promotional discount or gets flagged for manual review.
package org.syuthd.rules.example;
import org.syuthd.rules.Rule;
import org.syuthd.rules.RuleEvaluator;
import org.syuthd.rules.domain.*;
import java.util.List;
public class CheckoutService {
// Construct a composite rule tree programmatically
public Rule<OrderPayload> buildVIPDiscountRule() {
// Condition 1: Order total must be over $250.00
Rule<OrderPayload> spendRule =
new Rule.GreaterThan<>(OrderPayload::amount, 250.00);
// Condition 2: Customer risk score must be low (less than or equal to 20)
// Expressed as NOT (risk score > 20)
Rule<OrderPayload> lowRiskRule =
new Rule.Not<>(new Rule.GreaterThan<>(
o -> (double) o.customer().riskScore(), 20.0
));
// Combine using logical AND
return new Rule.And<>(List.of(spendRule, lowRiskRule));
}
public void processCheckout(OrderPayload payload) {
Rule<OrderPayload> discountEligibility = buildVIPDiscountRule();
boolean getsDiscount = RuleEvaluator.evaluate(discountEligibility, payload);
if (getsDiscount) {
System.out.println("Applying 15% VIP discount to order: " + payload.orderId());
} else {
System.out.println("Standard pricing applied to order: " + payload.orderId());
}
}
}The code sample above creates a typed, reusable rule composition that lives entirely within standard application code. There are no XML files, dynamic dynamic evaluation contexts, or string expressions to maintain.
This approach runs at native JVM execution speeds, allowing the compiler to optimize the pattern match into streamlined bytecode. The performance matches hand-written if-else branches while retaining abstract composition capability.
Build fluent builder APIs or static helper factories around your AST record constructors (e.g., Rules.and(ruleA, ruleB)) to keep complex rules readable and domain-focused across engineering teams.
Rule Engine Architectural Comparison
Choosing the right logic engine pattern is critical for long-term codebase maintainability. The chart below summarizes how this modern algebraic approach compares to traditional rule processing strategies.
| Feature Category | Legacy String/SpEL Engines | Reflection/Annotation Frameworks | Modern Java ADT Rule Engine |
|---|---|---|---|
| Safety Verification | Runtime resolution (Fail late) | Startup inspection (Partial) | Compile-time validation (Fail early) |
| IDE Refactoring | Broken by field renames | Requires explicit plugin setup | 100% native IDE support |
| Execution Speed | Slow dynamic parsing | Reflection invocation overhead | Native bytecode performance |
| External Dependencies | Heavy dynamic dependencies | Medium library overhead | Zero dependencies (Pure Java) |
Best Practices and Common Pitfalls
Keep Nodes Pure Data
Never embed evaluation methods directly inside your record definitions (e.g., adding an evaluate() method on the Rule interface). Keeping AST models isolated from evaluation logic separates your data structures from their interpreters, allowing you to create alternative engines—such as SQL exporters or JSON serializers—without modifying core domain objects.
Watch Out for Record Pattern Exhaustiveness Gaps
When pattern matching over nested data structures, remember that record patterns match exact shapes. If a record component type changes, ensure your pattern switch expressions update accordingly to prevent unintended fallthrough behavior.
// WRONG: Manually casting inside switch branches defeats type safety
public static boolean evaluateUnsafe(Object obj) {
if (obj instanceof Rule.Equals eq) {
// Don't do untyped raw evaluation here!
}
return false;
}
// CORRECT: Fully typed record pattern extraction
public static <T> boolean evaluateSafe(Rule<T> rule, T target) {
return switch (rule) {
case Rule.Equals<T, ?> eq -> eq.extractor().apply(target).equals(eq.expectedValue());
// ... rest of exhaustive switch
default -> false; // Never use default on sealed hierarchies!
};
}The example above highlights the difference between legacy instance checks and modern deconstruction patterns. Avoid manual casting within branch logic, as it reintroduces runtime type exceptions.
Future Outlook and What's Coming Next
Modern Java's pattern matching capabilities continue to evolve rapidly. Upcoming releases aim to expand deconstruction capabilities beyond records to standard classes via explicit deconstruction patterns.
Furthermore, enhancements to primitive handling in pattern matching will allow primitive values to participate directly in patterns without boxing overhead. This change will make high-throughput, real-time rule engine AST evaluation faster and even more concise.
Conclusion
Building a type-safe rule engine in Java no longer requires third-party libraries or dynamic string parsers. By combining sealed interfaces, record types, and exhaustive switch expressions, you can construct custom rule engines that are completely type-safe, performant, and maintainable.
This design shifts logic validation from runtime execution to compile time. Renaming a payload field or introducing an unhandled rule type immediately triggers a build error, keeping your production deployment safe and stable.
Take the code patterns from this article, apply them to your current domain models, and eliminate dynamic string evaluators from your tech stack today.
- Sealed interfaces allow the Java compiler to guarantee exhaustive pattern matching without fallback branches.
- Java records provide immutable value representation, making rule nodes thread-safe AST structures.
- Record patterns let you unpack complex domain models cleanly inside single switch expression branches.
- Replacing string reflection with strongly typed extractors catches domain model breaking changes at compile time.