Post

Misuse of Java8 Optional

  1. The intent of Java when releasing Optional was to use it as a return type
  2. The practice of using Optional as a method parameter is even discouraged by some code inspectors.
1
2
3
4
5
6
7
public staic List<Person> search(List<Person> people, String name, Optional<Integer> age) {
	// Null checks for people and name
	return people.stream()
			.filter(p -> p.getName().equals(name))
			.filter(p -> p.getAge().get() >= age.orElse(0))
			.collect(Collectors.toList());
}

And another developer tries to use it:

1
2
someObject.search(people, "Peter", null);
// gets a NullPointerException!
This post is licensed under CC BY 4.0 by the author.