My Profile Photo

Hao's Keeper


A blog to place memos


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.
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:

someObject.search(people, "Peter", null);
// gets a NullPointerException!