Item 55: Return optionals judiciously
55. Be careful when returning Optional
- Prior to Java7, when considering methods that couldn't return a value under certain conditions, there was no choice but to throw an exception or return null. From Java8, the option to return Optional was born.
package tryAny.effectiveJava;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
public class OptionalTest {
public static void main(String[] args) {
List<String> l1 = Arrays.asList("paper", "strong", "java", "pepper");
List<String> l2 = new ArrayList<>();
System.out.println(max(l1).get());
System.out.println(max(l2).orElse("no words"));
try {
max(l2).orElseThrow();
} catch (NoSuchElementException e) {
System.out.println(e.getMessage());
}
System.out.println(max(l1).filter(str -> str.length() == 6).map(str -> str.toUpperCase()).get());
}
public static <E extends Comparable<E>> Optional<E> max(Collection<E> c) {
if (c.isEmpty()) {
return Optional.empty();
}
E result = null;
for (E ele : c) {
if (result == null || ele.compareTo(result) > 0) {
result = Objects.requireNonNull(ele);
}
}
return Optional.of(result);
}
}
- Do not return null from a method for which Optional is the return value. If you do this, there is no point in introducing Optional.
- When choosing whether to return Optional instead of returning null or throwing an exception, choose with the same idea (Item71) as deciding whether to throw a checked exception.
- You should not wrap in Optional for anything that stores something like a collection, map, stream, array, Optional. For example, it is better to return an empty List than to return an Optional <List >. This is because if you can return an empty List , you don't need to return Optional in the first place.
- When you should select an Optional wrapped value as the return value of the method, it may not be possible to return the result, and if the result is null, the method caller needs special consideration. Is.
- Do not return Optional for int, double, long wrapper classes. OptionalInt, OptionalDouble, and OptionalLong are available, so use them.
- Do not use Optional as a collection, array key, value, or element.
- It is possible to use Optional as a non-essential field value for an instance. (Refer to the class handled in Item2)