Wikidata-Toolkit
Wikidata-Toolkit copied to clipboard
Replace nulls by `Optional`
To ensure the type safety of the code it may be nice to use the Java 8 Optional construction where it is relevant.
I am not sure that we actually want to do it because Optional is not available on Android versions before the quite new 7.0.
Even Optional wouldn't be enough.
Optional is an improvement as it lets API users decide what to do about missing values (fallback, null, throw). But I noticed many methods return null if they cannot choose between two possible results. In these cases, even Optional wouldn't provide callers with sufficient choice.
These methods just have to return List. To make them more convenient, it is possible to define Ambiguous (not sure about the name) that would inherit from List and also provide API inspired by Optional for cases when only one item is expected by the application.
public interface Ambiguous<T> extends List<T> {
static Ambiguous<T> empty();
static Ambiguous<T> of(T value);
static Ambiguous<T> ofNullable(T value);
static Ambiguous<T> of(T... values);
boolean isPresent(); // 1 or more
boolean isUnique(); // 0 or 1
boolean isAmbiguous(); // 2 or more
boolean isSingle(); // exactly 1
Optional<T> unique(); // throws if there are 2+ items
Optional<T> uniqueOrElse(T fallback); // fallback if there are 2+ items
Optional<T> uniqueOrElseGet(Supplier<? extends T> supplier);
T single(); // throws if there are 0 or 2+ items
T singleOrElse(T fallback); // fallback if there are 0 or 2+ items
T singleOrElseGet(Supplier<? extends T> supplier);
}
Application interested in picking one of the values could just use stream() method.
So methods that query values guaranteed to be unique would return Optional while possibly ambiguous results would be typed Ambiguous.