Don’t pass null as an explicit argument into a method. The problem with passing null as an explicit value into a method is very similar to that of passing explicit bool values into a method - the code is fundamentally unreadable.

Consider this simple example - imagine that you’re working on some kind of accounting system and you find use of a method that applies pricing to an invoice:

currentInvoice.ApplyPricing(null);

Do you know what the null value means? Does it become any clearer when you read the method declaration?

public void ApplyPricing(IDiscountPolicy discountPolicy) 
{ 
    //... 
}

What does a null discount policy do?

Requiring consumers of your code to pass in an explicit null value is a code smell, highlighting an area of the system that needs improvement.

One way to solve our particular example situation is to split the two approaches into two separate methods:

public void ApplyRetailPricing()
{ 
    // ... 
}

public void ApplyDiscountPricing(IDiscountPolicy discountPolicy) 
{ 
    discountPolicy.MustNotBeNull(nameof(discountPolicy));
    // ... 
}

Observe that ApplyDiscountPricing() now requires that a policy is provided and will throw an ArgumentNullException if null is explicitly passed.

Another way to solve the problem is to make it really easy to always provide a policy by introducing an easy way to get a suitable value:

currentInvoice.ApplyPricing(DiscountPolicy.RetailPricing);

We introduced the static class DiscountPolicy to make it easy for the code to find the retail pricing policy to use. We also modified the implementation of ApplyPricing to throw an ArgumentNullException if null is explicitly passed.

If it is difficult or impossible to modify the code to eliminate the null value, you should at least use the C# optional argument syntax to provide a label for the value:

currentInvoice.ApplyPricing(discountPolicy: null);

While this isn’t much better, you’re at least giving more information to any reader of the code to they don’t have to guess quite so much (though they still won’t know how the null is used).

Use this approach as a very rare last resort, however - it’s far better to address the problem at its root by fixing the underlying problem.

Various code analysis tools (including Resharper) will suggest removing the argument name discountPolicy because it’s technically redundant. In this case, however, the argument name is included for the benefit of the reader, not the compiler, and it should be retained.

Prior post in this series:
Don't work too hard
Next post in this series:
Are Boolean Return values Evil?

Comments

blog comments powered by Disqus