-
Notifications
You must be signed in to change notification settings - Fork 0
Introduction
Very often we write code like the following:
String phone = person.getSpouse().getCompany().getPresident().getSecretary().getPhone();
Very often we want to get the phone number of secretary of the president of company where the current person's spouse works or nothing, i.e. it does not matter whether the person is single, his spouse does not work, the president does not employ secretary or the secretary does not have phone. In all these case the line written above will throw NullPointerException. To prevent it we have to write code like this:
Person spouse = person.getSpouse();
if (spouse != null) {
Company company = spouse.getCompany();
if (company != null) {
Manager president = company.getPresident();
if (president != null) {
Person secretary = president.getSecretary();
if (secretary != null) {
String phone = secretary.getPhone();
}
}
}
}
And all these just to prevent NPE!
OK, other way is to catch NullPointerException:
String phone;
try {
phone = person.getSpouse().getCompany().getPresident().getSecretary().getPhone();
} catch (NullPointerException e) {
phone = null;
}
This code is much shorter but it is definitely bad style. The exception might be thrown from any method in chain. Catching exception here may hide real problem in code or environment.
So, the motivation is to create something like smart reference that causes the whole chain to return null when at least one method in chain returns null instead of throwing NullPointerException.
Another example is when chain contains collection or array:
Date birthdayOfOlderChild = person.getChildren().iterator().next().getBirthday();
If person does not have children NoSuchElementException will be thrown here. But we just wanted to get the birthday of older child or nothing.
It means that the library should be safe to collection bounds violations.
Link to repository: Sonatype repository