Java Reference
In-Depth Information
1 Notable exceptions include most typed functional languages, such as Haskell and ML; these
include algebraic data types that allow data types to be succinctly expressed, including explicit
specification of whether special values such as null are to be included on a type-by-type basis.
10.1. How do you model the absence of a value?
Imagine you have the following nested object structure for a person owning a car and having car
insurance.
Listing 10.1. The Person / Car / Insurance data model
public class Person {
private Car car;
public Car getCar() { return car; }
}
public class Car {
private Insurance insurance;
public Insurance getInsurance() { return insurance; }
}
public class Insurance {
private String name;
public String getName() { return name; }
}
Then, what's possibly problematic with the following code?
public String getCarInsuranceName(Person person) {
return person.getCar().getInsurance().getName();
}
This code looks pretty reasonable, but many people don't own a car. So what's the result of
calling the method getCar? A common unfortunate practice is to return the null reference to
indicate the absence of a value, here to indicate the absence of a car. As a consequence, the call
to getInsurance will return the insurance of a null reference, which will result in a
NullPointerException at run-time and stop your program from running further. But that's not
all. What if person was null? What if the method getInsurance returned null too?
 
Search WWH ::




Custom Search