remove 'name' from Rule
[reguloj.git] / src / main / java / wtf / metio / reguloj / Rule.java
blob310762a0221118a9dc91127806874917ee63ef29
1 /*
2 * SPDX-FileCopyrightText: The reguloj Authors
3 * SPDX-License-Identifier: 0BSD
4 */
5 package wtf.metio.reguloj;
7 import java.util.function.Consumer;
8 import java.util.function.Predicate;
10 /**
11 * <p>
12 * A {@link Rule} combines {@link java.util.function.Predicate} and {@link java.util.function.Consumer} interfaces and
13 * can be evaluated with a {@link RuleEngine} using a {@link Context}.
14 * </p>
15 * <h2>Examples</h2>
16 * <ol>
17 * <li>
18 * <p>
19 * Check whether a rule would fire inside a given context:
20 * </p>
22 * <pre>
23 * Context&lt;X&gt; context = ...;
24 * Rule&lt;Context&lt;X&gt;&gt; rule = ...;
26 * boolean canFire = rule.fires(context);
27 * </pre>
29 * </li>
30 * <li>
31 * <p>
32 * Run a rule inside a given context:
33 * </p>
34 * <pre>
35 * Context&lt;X&gt; context = ...;
36 * Rule&lt;Context&lt;X&gt;&gt; rule = ...;
38 * rule.run(context);
39 * </pre>
40 * </li>
41 * </ol>
43 * @param <CONTEXT> The context type.
44 * @see RuleEngine
45 * @see RuleBuilder
46 * @see Context
48 public interface Rule<CONTEXT extends Context<?>> {
50 /**
51 * Start building a new Rule by specifying a Predicate.
53 * @param <CONTEXT> The context type.
54 * @return A new builder to construct rules.
56 static <CONTEXT extends Context<?>> RuleBuilder<CONTEXT> when(final Predicate<CONTEXT> predicate) {
57 return new FluentRuleBuilder<CONTEXT>().when(predicate);
60 /**
61 * Create a new Rule that always fires/runs and calls the given Consumer.
63 * @param <CONTEXT> The context type.
64 * @return A new builder to construct rules.
66 static <CONTEXT extends Context<?>> Rule<CONTEXT> always(final Consumer<CONTEXT> consumer) {
67 return new FluentRuleBuilder<CONTEXT>().when(c -> true).then(consumer);
70 /**
71 * Checks whether this rule would fire for a given context.
73 * @param context The context to check.
74 * @return <code>true</code> if this rule would fire, <code>false</code> otherwise.
76 boolean fires(CONTEXT context);
78 /**
79 * Runs this rule inside a given context. A rule should only run iff {@link #fires(Context)} returns
80 * <code>true</code>.
82 * @param context The context to use.
84 void run(CONTEXT context);