Don’t pass null

A method declaration is a contract between the caller and the callee. And if the callee states the parameters then the callee should be responsible enough to not pass null. By passing a null you are breaking that contract and the caller should not expect the method to behave properly in this case. That is why I don’t check the parameters of my methods for null – if someone passes me a null, they should expect a NullPointerException.

If you are defining a method with an optional parameter, you should overload the method. The caller can then decide which contract they are going to make with the callee. It should be up to the caller to decide which behavior is expected. It shouldn’t be up to the callee to try to determine what the caller’s intention is.

If you are tempted to just pass null from the overloaded method to the second method to avoid code duplication, don’t! As soon as you do this you are doing 2 things: first, you are breaking your own contract by passing a null. Secondly, you are now tightly coupling 2 methods with different behaviors and expectations together. Instead, to avoid duplication, look at the commonality between the methods and pull out smaller, finer-grained methods.

Leave a Reply

Your email address will not be published. Required fields are marked *