As others suggested, the code can be simplified, but why not make a chain of calls, as well as the final class, so you will have a simple and clean model:
final class Checker<T> { private final T value; private final UnaryOperator<T> callback; private Checker(T value, UnaryOperator<T> callback) { this.value = value; this.callback = callback; } public static <T> Checker<T> when(T t) { return new Checker<>(t, UnaryOperator.identity()); } public Checker<T> then(UnaryOperator<T> callback) { return new Checker<>(value, t -> callback.apply(this.callback.apply(t))); } public T execute() { return callback.apply(value); } }
Instead of returning this to then() , this approach returns a completely new Checker instance
source share