Although it may look dirty, I prefer to replace one of the final links with Supplier (for example, in Guava or Java 8 ), for example:
class A { final Supplier<B> b; A(Supplier<B> b) { this.b = b; }
where the MutableSupplier looks something like this:
import com.google.common.base.Supplier; public class MutableSupplier<T> implements Supplier<T> { private boolean valueWasSet; private T value; private MutableSupplier() { } @Override public T get() { if (!valueWasSet) { throw new NullPointerException("Value has not been set yet"); } return value; } public T set(final T value) { if (valueWasSet) { throw new IllegalStateException("Value has already been set and should not be reset"); } this.value = value; this.valueWasSet = true; return value; } public static <T> MutableSupplier<T> create() { return new MutableSupplier<T>(); } }
I know that the mutability of MutableSupplier looks super-ugly for immutability enthusiasts, but I found that using such methods is more or less acceptable in such cases :)
source share