null considered harmful
- November 18th, 2009
- Write comment
By incident I stumbled accross the book “Clean Code: A Handbook of Agile Software Craftsmanship” by Robert C. Martin. In this book there is a section on exception handling which is a worthwhile read. It states some obvious things – like handle exceptions there where you know what to do with them — but it is good to be remembered by these best practices once in a while…
One of the more interesting things in that section I found the usage, or better should-not-usage, of null values. Return null is typically a sign of something that doesn’t work. Returning null values clutters op code with all kinds of “if null” checks. Moreover, who hasn’t seen a NullReferenceException lately? Instead of returning null, a number of alternatives can be thought of:
First, if the null is actually the result of an error conditions, throw an exception containing thate error condition. If the error is actually based on a deeper lying exception, simply don’t handle that exception and have it bubble upwards. This way it is clear to the user of our object/method that an error condition has been met. Moreover, the exception should contain the necessary information to aid the programmer in preventing that condition.
Second, if the null value is the result of an expected situation, implement the “Null Object Pattern”, or “Special Case Pattern” instead. Using these patterns you return an object that implements the expected interface, but which implementation is empty. For example, a search for files in an empty directory should return an empty list instead of null. The empty list can be iterated, checked for presence of files, but does not have to be explicitly checked for null.