Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace nulls by Optional #327

Open
Tpt opened this issue Mar 5, 2018 · 2 comments
Open

Replace nulls by Optional #327

Tpt opened this issue Mar 5, 2018 · 2 comments

Comments

@Tpt
Copy link
Collaborator

Tpt commented Mar 5, 2018

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

@Tpt
Copy link
Collaborator Author

Tpt commented Jul 4, 2018

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.

@robertvazan
Copy link
Collaborator

robertvazan commented Feb 3, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants