Wednesday, February 27, 2013

Nulls Are Mostly Harmful

This is an old thing, but it should be emphasized again and again. Nulls are mostly harmful, because
  • they force programmers to pollute the code with null checks
  • uninitialized references may easily cause runtime errors
  • null semantics is ambiguous, null may represent
    • an unintentionally uninitialized reference
    • a legal value (an intentionally uninitialized reference)
    • a lack of result of an operation
    • a result of a failed operation
    • a result of a human (usually programming) error
    • etc.
So avoid them by using
  • defensive programming practices
    • never return null, only in the rare case when the operation has clear semantics, and
    • explicitly document this decision in a formal way (e.g. using the javax.annotation.Nullable annotation)
    • use the Null Object design pattern if you should represent a legal null value
    • annotate the code with javax.validation.constraints.NotNull to be able to verify runtime reference nullness
  • validation using static and runtime analysis
    • static analysis is fast and well-integrated with most of the popular IDEs (see The Checker Framework and FindBugs), but it only finds errors that can be detected in compile-time
    • runtime analysis is more accurate, but slower and requires a testing phase in the development process (see Java Pathfinder and Hibernate Validator).