Value: rewrite using strong chaining logic

Return values from each step restrict next chained method(s) available.
This commit is contained in:
Paul Campbell 2017-04-23 17:11:37 +01:00
parent 598f69a65b
commit 06c9487eea

View file

@ -5,52 +5,103 @@ import java.util.function.Supplier;
/** /**
* @author Paul Campbell (pcampbell@kemitix.net). * @author Paul Campbell (pcampbell@kemitix.net).
*/ */
public class Value<T> { public interface Value<T> {
private boolean clause; static <T> ValueClause<T> where(final boolean clause) {
if (clause) {
private Supplier<T> trueSupplier; return new TrueValueClause<>();
}
private Value(final boolean clause) { return new FalseValueClause<>();
this.clause = clause;
} }
static <T> Value<T> where(final boolean clause) { static <T> ValueClause<T> whereNot(boolean clause) {
return new Value<>(clause);
}
static <T> Value<T> whereNot(final boolean clause) {
return where(!clause); return where(!clause);
} }
Value<T> then(final Supplier<T> trueSupplier) { interface ValueClause<T> {
this.trueSupplier = trueSupplier;
return this;
}
T otherwise(final Supplier<T> falseSupplier) { ValueSupplier<T> then(Supplier<T> trueSupplier);
if (clause) {
return trueSupplier.get(); ValueClause<T> and(boolean clause);
ValueClause<T> or(boolean clause);
default ValueClause<T> andNot(final boolean clause) {
return and(!clause);
} }
return falseSupplier.get();
default ValueClause<T> orNot(boolean clause) {
return or(!clause);
}
interface ValueSupplier<T> {
T otherwise(Supplier<T> falseSupplier);
}
} }
Value<T> and(final boolean clause) { class TrueValueClause<T> implements ValueClause<T> {
this.clause = this.clause && clause;
return this; @Override
public ValueSupplier<T> then(final Supplier<T> trueSupplier) {
return new TrueValueSupplier<T>(trueSupplier);
}
@Override
public ValueClause<T> and(final boolean clause) {
return Value.<T>where(clause);
}
@Override
public ValueClause<T> or(final boolean clause) {
return this;
}
private class TrueValueSupplier<T> implements ValueSupplier<T> {
private final Supplier<T> valueSupplier;
TrueValueSupplier(final Supplier<T> valueSupplier) {
this.valueSupplier = valueSupplier;
}
@Override
public T otherwise(final Supplier<T> falseSupplier) {
return valueSupplier.get();
}
}
} }
Value<T> or(final boolean clause) { class FalseValueClause<T> implements ValueClause<T> {
this.clause = this.clause || clause;
return this;
}
Value<T> andNot(final boolean clause) { @Override
return and(!clause); public ValueSupplier<T> then(final Supplier<T> trueSupplier) {
} return new FalseValueSupplier<T>();
}
@Override
public ValueClause<T> and(final boolean clause) {
return this;
}
@Override
public ValueClause<T> or(final boolean clause) {
return Value.<T>where(clause);
}
private class FalseValueSupplier<T> implements ValueSupplier<T> {
@Override
public T otherwise(final Supplier<T> falseSupplier) {
return falseSupplier.get();
}
}
Value<T> orNot(final boolean clause) {
return or(!clause);
} }
} }