2 SPDX-FileCopyrightText: The reguloj Authors
3 SPDX-License-Identifier: 0BSD
6 # reguloj [![Chat](https://img.shields.io/badge/matrix-%23talk.metio:matrix.org-brightgreen.svg?style=social&label=Matrix)](https://matrix.to/#/#talk.metio:matrix.org)
8 `reguloj` is a small and lightweight Java rule engine.
12 ### Creating rule engines
14 A rule engine evaluates a set of rules in a specific context. The `RuleEngine` interface offers 3 factory methods to build rule engines:
17 // All rules will be evaluated indefinitely until no further rule fires.
18 RuleEngine<CONTEXT> chained = RuleEngine.chained();
20 // All rules will be evaluated, but only a maximum number of 5 times.
21 RuleEngine<CONTEXT> limited = RuleEngine.limited(5);
23 // Evaluates all rules, stops after the first one that fires.
24 RuleEngine<CONTEXT> firstWins = RuleEngine.firstWins();
27 All provided rule engines are thread-safe and can be used as often as you like. If custom inference behavior is required, subclass `AbstractRuleEngine` and implement the `infer()` method. The following code example shows how to work with rule engines:
30 // setup - more details later
31 RuleEngine<CONTEXT> engine = ...;
32 Collection<Rule<CONTEXT>> rules = ...;
33 CONTEXT context = ...;
35 // true if at least one rule can fired.
36 engine.analyze(rules, context);
38 // perform conclusions of those rules that fired.
39 engine.infer(rules, context);
42 Note that the order of the collection dictates the evaluation order of your rules - if order does matter, use `List` rather than `Set` as a `Collection` implementation.
46 A [rule](https://github.com/metio/reguloj/blob/main/src/main/java/wtf/metio/reguloj/Rule.java) has a name and runs in a given context. Additionally, it can be checked whether a rule fires in a given context.
48 Either implement the `Rule` interface yourself and or use the supplied rule implementation and builder. A standard rule is composed of a `java.util.function.Predicate` and `java.util.function.Consumer`. Both interfaces require you to implement only a single method and do not restrict you in any way. Complex rules can be created by grouping or chaining predicates/consumers together with the help of several utility methods. The following example creates a rule composed of 2 predicates and 2 consumers:
51 Rule<CONTEXT> rule = Rule.called(name)
52 .when(predicate1.and(predicate2))
53 .then(consumer1.andThen(consumer2));
55 // true if the rule would fire in the given context, e.g. the above predicate is true.
58 // runs (applies) the rule in the given context
62 Using Java 8 lambdas is possible as well:
65 Rule<CONTEXT> rule = Rule.called(name)
66 .when(context -> context.check())
67 .then(context -> context.action())
70 Note that custom implementations of the `Rule` interface don't necessary have to use the `java.util.function` package and are free to choose how their implementation looks like.
72 ### Creating an inference context
74 An inference [context](https://github.com/metio/reguloj/blob/main/src/main/java/wtf/metio/reguloj/Context.java) contains information needed by predicates and/or consumers. This project supplies a simple implementation of the Context interface called `SimpleContext` which just wraps a given topic. The `AbstractContext` class can be used to create subclasses in case your rules need extra information. The API acknowledges this by using `<CONTEXT extends Context<?>>` as type parameter for all methods which expect a Context, thus allowing all context implementations to be used. See item 28 in Effective Java for more details.
77 CONTEXT context = Context.of("some object");
82 The [wtf.metio.regoluj.shoppingcart](https://github.com/metio/reguloj/tree/main/src/test/java/wtf/metio/reguloj/shoppingcart) package contains [tests](https://github.com/metio/reguloj/blob/main/src/test/java/wtf/metio/reguloj/shoppingcart/ShoppingCartTest.java) for an example use case revolving around shopping carts, products, and their prices. It works as follows:
84 We have a custom `Context` implementation in the form of [wtf.metio.regoluj.shoppingcart.Cart](https://github.com/metio/reguloj/blob/main/src/test/java/wtf/metio/reguloj/shoppingcart/Cart.java) that holds a list of products, and a matching list of prices for those products. The list of products is its main topic. Various `Rules` are used to calculate the price per product in the shopping cart. Written as a `record`, the `Cart` could look like this:
87 public record Cart(List<Product> topic, List<Price> prices) implements Context<List<Product>> {
92 As you can see, one of the `record` parameters must be named `topic` and use the type of the context in order to correctly implement the method contract of `Context`. Similar, a `Product` and `Price` could look like this:
95 public record Product(String name) {
99 public record Price(Product product, int price) {
104 The initial state of a card contains just the products without any previously calculated prices in this example:
107 final Cart singleProductCart = new Cart(List.of(TEST_PRODUCT), new ArrayList<>());
108 final Cart multiProductCart = new Cart(List.of(TEST_PRODUCT, TEST_PRODUCT), new ArrayList<>());
111 The constant `TEST_PRODUCT` is just some example data that represents objects of your actual business domain: `Product TEST_PRODUCT = new Product("xPhone 37");`.
113 ### Using RuleEngine#firstWins
116 RuleEngine<Cart> ruleEngine = RuleEngine.firstWins();
119 While using a first-wins `RuleEngine`, our `Rules`s could look like this:
122 final var standardPrice = Rule.<Cart>called("single purchase uses standard price")
123 .when(cart -> true) // always fires thus can be used as a fallback
124 .then(cart -> cart.prices().add(new Price(TEST_PRODUCT, 100)));
125 final var reducedPrice = Rule.<Cart>called("multiple purchases get reduced price")
126 .when(cart -> cart.topic().size() > 1) // only fires for multiple products
127 .then(cart -> cart.prices().add(new Price(TEST_PRODUCT, 75 * cart.topic().size())));
130 As you can see, we kept the implementation of the rules rather simple, in order to keep the example focused on the `reguloj` related classes. In a real world project, you don't want to specify a constant price for a single product, but rather use some database lookup or similar technique to calculate prices more dynamically. Since we need both a `Context` and a `Collection` of rules, we combine the above into a `List` with:
133 Collection<Rule<Cart>> rules = List.of(reducedPrice, standardPrice);
136 The order is important here - we first test if we can apply the reduced priced, and only apply the full price as a fallback. In order to infer a price for our shopping carts, combine `Rules` and `Context` (carts) using the previously built `RuleEngine` as the following example shows:
139 ruleEngine.infer(rules, singleProductCart);
140 ruleEngine.infer(rules, multiProductCart);
143 Since the above rules will only ever add one price, we can check whether everything works as expected like this:
146 Assertions.assertEquals(100, singleProductCart.prices().get(0).price())
147 Assertions.assertEquals(150, multiProductCart.prices().get(0).price())
150 ### Using RuleEngine#limited
153 RuleEngine<Cart> ruleEngine = RuleEngine.limited(1);
156 While using a limited `RuleEngine`, our `Rules`s could look like this:
159 final var standardPrice = Rule.<Cart>called("single purchase uses standard price")
160 .when(cart -> cart.topic().size() == 1) // fires for single products
161 .then(cart -> cart.prices().add(new Price(TEST_PRODUCT, 100)));
162 final var reducedPrice = Rule.<Cart>called("multiple purchases get reduced price")
163 .when(cart -> cart.topic().size() > 1) // fires for multiple products
164 .then(cart -> cart.prices().add(new Price(TEST_PRODUCT, 75 * cart.topic().size())));
167 The difference here is that the first rule only fires for carts that contain a single product (remember the topic of a cart is a list of products) since a limited `RuleEngine` will try ever rule a limited number of times and thus it won't stop after some rule fired as in the first example. Note that this implementation would have worked in the first example as well, however the first example would not work with a limited `RuleEngine`. The implementation for the second rule is exactly the same as the first example.
170 Collection<Rule<Cart>> rules = Set.of(standardPrice, reducedPrice);
173 Since the order in which rules are fired does not matter, we can use a `Set` rather than `List`. In case you are planning on creating rules dynamically based on some external data, like XML, YAML, a database, or your neighbours dog, make sure to be a specific as possible in your predicates in order to make your rules as widely usable as possible.
176 ruleEngine.infer(rules, singleProductCart);
177 ruleEngine.infer(rules, multiProductCart);
179 Assertions.assertEquals(100, singleProductCart.prices().get(0).price())
180 Assertions.assertEquals(150, multiProductCart.prices().get(0).price())
183 Running the inference process is exactly the same no matter which `RuleEngine` you picked or how you `Rule`s are implemented.
185 ### Using RuleEngine#chained
188 RuleEngine<Cart> ruleEngine = RuleEngine.chained();
191 While using a chained `RuleEngine`, our `Rules`s could look like this:
194 final var standardPrice = Rule.<Cart>called("single purchase uses standard price")
195 .when(cart -> cart.topic().size() == 1 && cart.prices().size() == 0)
196 .then(cart -> cart.prices().add(new Price(TEST_PRODUCT, 100)));
197 final var reducedPrice = Rule.<Cart>called("multiple purchases get reduced price")
198 .when(cart -> cart.topic().size() > 1 && cart.prices().size() == 0)
199 .then(cart -> cart.prices().add(new Price(TEST_PRODUCT, 75 * cart.topic().size())));
202 Since chained `RuleEngine`s will run all `Rule`s as often as they fire, we need an extra terminal condition to stop re-firing our rules. Since we are only calculating the price of a single product, we can always stop firing our `Rule`s in case there is already a price in our cart.
205 Collection<Rule<Cart>> rules = Set.of(standardPrice, reducedPrice);
208 Again, the order of our rules do not matter, thus we are using a `Set`.
211 ruleEngine.infer(rules, singleProductCart);
212 ruleEngine.infer(rules, multiProductCart);
214 Assertions.assertEquals(100, singleProductCart.prices().get(0).price())
215 Assertions.assertEquals(150, multiProductCart.prices().get(0).price())
218 Getting a final price for our carts is exactly the same again.
224 <groupId>wtf.metio.reguloj</groupId>
225 <artifactId>reguloj</artifactId>
226 <version>${version.reguloj}</version>
232 implementation("wtf.metio.reguloj:reguloj:${version.reguloj}") {
233 because("we want to use a lightweight rule engine")
238 Replace `${version.reguloj}` with the [latest release](http://search.maven.org/#search%7Cga%7C1%7Cg%3Awtf.metio.reguloj%20a%3Areguloj).
243 |------------|------|
249 In case `reguloj` is not what you are looking for, try these projects:
251 - [Dredd](https://github.com/amsterdatech/Dredd)
252 - [SmartParam](https://github.com/smartparam/smartparam)
253 - [ramen](https://github.com/asgarth/ramen)
254 - [nomin](https://github.com/dobrynya/nomin)
255 - [dvare](https://github.com/dvare/dvare-rules)
256 - [ruli](https://github.com/mediavrog/ruli)
257 - [MintRules](https://github.com/augusto/MintRules)
258 - [Jare](https://github.com/uwegeercken/jare)
259 - [tuProlog](http://alice.unibo.it/xwiki/bin/view/Tuprolog/)
260 - [drools](https://www.drools.org/)
261 - [Easy Rules](https://github.com/j-easy/easy-rules)
262 - [n-cube](https://github.com/jdereg/n-cube)
263 - [RuleBook](https://github.com/deliveredtechnologies/rulebook)
264 - [OpenL Tablets](http://openl-tablets.org/)
265 - [JSR 94](https://jcp.org/en/jsr/detail?id=94)
266 - [rules](https://github.com/rlangbehn/rules)
271 Permission to use, copy, modify, and/or distribute this software for any
272 purpose with or without fee is hereby granted.
274 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
275 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
276 FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
277 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
278 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
279 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
280 PERFORMANCE OF THIS SOFTWARE.
285 - https://github.com/metio/reguloj
286 - https://gitlab.com/metio.wtf/reguloj
287 - https://codeberg.org/metio.wtf/reguloj
288 - https://bitbucket.org/metio-wtf/reguloj