Wikidata-Toolkit icon indicating copy to clipboard operation
Wikidata-Toolkit copied to clipboard

Replace nulls by `Optional`

Open Tpt opened this issue 7 years ago • 2 comments

To ensure the type safety of the code it may be nice to use the Java 8 Optional construction where it is relevant.

Tpt avatar Mar 05 '18 15:03 Tpt

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.

Tpt avatar Jul 04 '18 16:07 Tpt

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.

robertvazan avatar Feb 03 '21 08:02 robertvazan