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).
*/
public class Value<T> {
public interface Value<T> {
private boolean clause;
private Supplier<T> trueSupplier;
private Value(final boolean clause) {
this.clause = clause;
static <T> ValueClause<T> where(final boolean clause) {
if (clause) {
return new TrueValueClause<>();
}
return new FalseValueClause<>();
}
static <T> Value<T> where(final boolean clause) {
return new Value<>(clause);
}
static <T> Value<T> whereNot(final boolean clause) {
static <T> ValueClause<T> whereNot(boolean clause) {
return where(!clause);
}
Value<T> then(final Supplier<T> trueSupplier) {
this.trueSupplier = trueSupplier;
return this;
}
interface ValueClause<T> {
T otherwise(final Supplier<T> falseSupplier) {
if (clause) {
return trueSupplier.get();
}
return falseSupplier.get();
}
ValueSupplier<T> then(Supplier<T> trueSupplier);
Value<T> and(final boolean clause) {
this.clause = this.clause && clause;
return this;
}
ValueClause<T> and(boolean clause);
Value<T> or(final boolean clause) {
this.clause = this.clause || clause;
return this;
}
ValueClause<T> or(boolean clause);
Value<T> andNot(final boolean clause) {
default ValueClause<T> andNot(final boolean clause) {
return and(!clause);
}
Value<T> orNot(final boolean clause) {
default ValueClause<T> orNot(boolean clause) {
return or(!clause);
}
interface ValueSupplier<T> {
T otherwise(Supplier<T> falseSupplier);
}
}
class TrueValueClause<T> implements ValueClause<T> {
@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();
}
}
}
class FalseValueClause<T> implements ValueClause<T> {
@Override
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();
}
}
}
}