Building Rules (Declarative)
Annotation-based rules let you define rules as Java classes with annotated methods. This style is ideal for complex rules that benefit from encapsulation, constructor parameters, and reusability.
Basic Structure
Section titled “Basic Structure”@Rule(name = "ConsistentDateRule")public class ConsistentDateRule {
@PreCondition public boolean shouldRun(LocalDate startDate, LocalDate endDate) { return startDate != null && endDate != null; }
@Given public boolean isValid(LocalDate startDate, LocalDate endDate) { return !endDate.isBefore(startDate); }
@Then public void passed() { System.out.println("Dates are consistent"); }
@Otherwise public void failed() { System.out.println("End date is before start date!"); }}Annotation Reference
Section titled “Annotation Reference”| Annotation | Returns | Purpose |
|---|---|---|
@Rule |
— | Marks the class as a rule (name, description) |
@PreCondition |
boolean |
Should this rule run? (optional) |
@Given |
boolean |
The IF condition |
@Then |
void |
Action when condition is true |
@Otherwise |
void |
Action when condition is false (optional) |
Multiple @Then Actions
Section titled “Multiple @Then Actions”You can have multiple @Then methods. Use the order attribute to control execution order:
@Then(order = 0)public void logResult() { System.out.println("Logging...");}
@Then(order = 1)public void notifyUser() { System.out.println("Notifying...");}Parameter Binding with @Param
Section titled “Parameter Binding with @Param”If your method parameter name doesn’t match the binding name, use @Param:
@Givenpublic boolean isValid(@Param("startDate") LocalDate start, @Param("endDate") LocalDate end) { return !end.isBefore(start);}Per-Run Local Bindings with LocalBindings (new in 2.2.0)
Section titled “Per-Run Local Bindings with LocalBindings (new in 2.2.0)”A method of a rule class that declares a parameter of type LocalBindings — on @PreCondition, @Given, @Then or @Otherwise — receives a fresh instance for each run of the rule, shared by every method of that run. What the pre-condition or the condition binds, the actions read. It is a plain Bindings (LocalBindings extends DefaultBindings), so bind, getValue and setValue all apply.
@Rule(name = "ShippingRule")public class ShippingRule {
@PreCondition public boolean shouldRun(Order order, LocalBindings local) { // Compute once, hand it to the rest of this run local.bind("weight", order.totalWeight()); return order.isShippable(); }
@Given public boolean isHeavy(LocalBindings local) { return local.<BigDecimal>getValue("weight").compareTo(LIMIT) > 0; }
@Then public void surcharge(LocalBindings local, Binding<BigDecimal> shipping) { BigDecimal weight = local.getValue("weight"); shipping.setValue(RATE.multiply(weight)); // the caller's binding, as usual }}- Nothing reaches the caller. The engine never binds the instance into the caller’s stack; it resolves the parameter from a per-run view over the caller’s live bindings. A rule’s actions still bind their outputs where the caller reads them, and the rule runs on an immutable context too.
- Never shared between runs. Recursive and concurrent runs of one rule each get their own instance; it is gone when the run ends.
- Conditions may write to it. Conditions receive their arguments as immutable copies; local bindings are the exception (
LocalBindings.asImmutable()returns itself), since handing something to the actions of the run is what they are for. - How it is matched. By the reserved name
localBindings(users cannot bind it) or by the exact typeLocalBindings. A parameter of typeBindingsnever resolves to it, and the reservedruleContextandbindingsstill resolve to the caller’s context and stack. - Class-based rules only. The declaration is read off the methods at build time and recorded as
RuleDefinition.usesLocalBindings(). A lambda-based rule declaring the parameter fails to build with anUnrulyException; a script has no parameters to declare.
Categorizing Rules with @Category and @Tags (new in 2.1.0)
Section titled “Categorizing Rules with @Category and @Tags (new in 2.1.0)”Two class-level annotations in org.rulii.annotation let a rule say where it belongs and what it is about, for tools that group and filter rules. Both sit beside @Rule and @Description, both are optional, and both are purely descriptive — rulii never reads them at execution time.
@Category("Pricing/Discounts")— at most one category per rule;/separates the levels of a hierarchy.@Tags({"vip", "discount"})— any number of tags, in the order given.
@Rule(name = "VipDiscountRule")@Description("Applies the VIP discount to qualifying orders")@Category("Pricing/Discounts")@Tags({"vip", "discount"})public class VipDiscountRule {
@Given public boolean qualifies(Customer customer) { return customer.isVip(); }
@Then public void applyDiscount(Order order) { order.applyDiscount(0.10); }}The values land on the rule’s RuleDefinition through the Categorized interface — getCategory() and getTags(). They are normalized on the definition: category levels are trimmed and empty levels dropped; tags are trimmed, blanks dropped, and duplicates kept once. Nothing is inferred from packages, files or names. See Introspection & Metadata for reading them back.
Building and Running
Section titled “Building and Running”// From class (new instance created automatically)Rule rule = Rule.builder().build(ConsistentDateRule.class);
// From instance (you control construction)Rule rule = Rule.builder().build(new ConsistentDateRule());
// Run it through a RuleFlow — the recommended wayRuleFlow<RuleContext> flow = RuleFlow.builder() .name("DateCheckFlow") .run(rule) .build();
flow.run( startDate -> LocalDate.of(2025, 1, 1), endDate -> LocalDate.of(2025, 12, 31));
// Registry-registered rules can also be referenced by class:// RuleFlow.builder().name("Flow").run(ConsistentDateRule.class).build()