2012/12/27

Append OrNull to a method that returns null

Introduction

  1. "A boy is told to buy a green Apple. He returns with a yellow Apple."
  2. "A boy is told to buy a green Apple. He returns with null."
  3. "A boy is told to buy a green Apple, if available. He returns with null."
  4. "A boy is told to buy a green Apple. He calls back from the Store to tell that a green Apple is not available."
Add#1: 
Do not return something else than asked for... unless the method name indicates so. 

Add#2: 
The return value null is an unexpected value. Returning it requires extra code on the calling side of a method call. If the extra code is missing, the null value may lead to errors that cannot easily be traced back to the method-call that returned null.

Add#3:
It is so easy to get this right. Simply append OrNull to your method name and return null. 
An alternative could be to have a bool argument e.g. allowNull or something, but that is much more cumbersome.

Add#4:
This is the default way of a method. Do what it is told or throw an exception. 
The method cannot solve this case, so the best thing is to tell the calling side so. In development this leads to run-time exceptions that should be avoided by modifying the code on the calling side. 


Description

The default way of making a method is to make it as simple as possible in such a way that it always fulfills its task. By default a method should return a non-null value or throw an exception. 

This rule is for the cases where null is an expected value. Returning null does not fulfill a task unless the method implies so. Hence, append OrNull to the name of method if it returns null. 

Returning null also requires the calling side to something extra. Therefore, when creating an OrNull method make sure to create a default version of the method too - one that throws an exception. If the calling side expects a non-null value, it will use this method instead.

Example

Default method TakeApple and TakeAppleOrNull alternative. CountApple is a related helper property.

Misc.:

- Use the FailFast principle (http://www.martinfowler.com/ieeeSoftware/failFast.pdf) whenever possible.
- When creating a method, consider if other related methods can help the calling side e.g. a Check/Exists/Count method.