I really hate null!
Reflect on that statement. Apparently Tim has a strong dislike for a concept found in lots of programming
languages (even brainiac languages like Haskell) and successfully used in millions of programs. He must be
crazy I wouldn’t like to have a discussion with him about something contentious like tabs versus spaces.
I understand that the world is an uncertain place and that programs need to represent uncertainty but I
don’t think null can be the correct way.
For example, consider this question: how many pets do you own? Is null a suitable answer?
Taking Java as the target for this polemic, which of Integer or int
is the best way to represent the number of pets you have?
Hint, one of those types can’t be null. Bonus question: what happens if you unbox an Integer
that holds a null value? Research topic: why does Java need boxed numeric types?
Some people have told me that they would use a type that can be null because they don’t know how many pets
that I own. Sorry, but I don’t think that is a good answer!
How would your program be different if you let zero be the default value for a quantity instead of null?
If their is uncertainty in a property would it be polite to let me know?
In order to guarantee that your program works correctly do you need to check that every
value is non-null before proceeding?
Is your code very hard to read and comprehend because of the huge number of null checks?
Or do you ignore that because all of your unit tests pass?
You do pass nulls into all your methods via your unit tests don’t you?
Now if we establish that Tim has 23 pets, how do we associate them with Tim?
I’d probably use List<Pet>.
Can a Collection contain nulls?
Can a collection be null?
Should you use null to represent an empty collection?
How would your program be different if you used Collections.emptyList() or
similar instead of null?
Should we stop programming and hope that JSR-305 makes it into the next version of the JDK?
Is their a refactoring in your IDE that will make Tim and his nulls go away?
Is it easier to press generate getters and setters in your IDE because no one you know would
pass in a null anyway at least not whilst you are still responsible for the project?
Do you think Tim is a wee bit upset about nulls in Java code?
Should he go and code in a more modern language?
Not necessarily! Guava can be quite helpful.
You don’t need to use Scala to get an Option type, Guava has Optional
Guava has immutable collections
that reject nulls.
Guava has handy pre-conditions
that you can use to prevent nulls entering at your constructors and setters.
Have I ranted for long enough about null?