Skip to content

defining facts

Mahmoud Ben Hassine edited this page May 17, 2020 · 10 revisions

A fact in Easy Rules is represented by the Fact API:

public class Fact<T> {
   private final String name;
   private final T value;
}

A fact has a name and a value, both must not be null. The Facts API on the other hand represents a set of facts and acts as a namespace of facts. This means facts must have unique names within a Facts instance.

Here is an example of how to define facts:

Fact<String> fact = new Fact("foo", "bar");
Facts facts = new Facts();
facts.add(fact);

You can also use a shorter version with the put method to create named facts as follows:

Facts facts = new Facts();
facts.put("foo", "bar");

Facts can be injected in rules condition and action methods using the @Fact annotation. In the following rule, the rain fact is injected in the rain parameter of the itRains method:

@Rule
class WeatherRule {

    @Condition
    public boolean itRains(@Fact("rain") boolean rain) {
        return rain;
    }

    @Action
    public void takeAnUmbrella(Facts facts) {
        System.out.println("It rains, take an umbrella!");
        // can add/remove/modify facts
    }

}

Parameters of type Facts will get injected all known facts (like in the takeAnUmbrella action method).

Heads up!

  • If an injected fact is missing in the condition method, the engine will log a warning and consider the condition as evaluated to false.
  • If an injected fact is missing in the action method, the action will not be performed and the engine will throw a org.jeasy.rules.core.NoSuchFactException.