Alex Rivera | Logout

Confused with Uncle Bob explanation on handling Null objects in book Clean Code

Asked 2011-06-16T12:40:45.690
9

I was reading Uncle Bob book today on Exception handling and what I could recollect from handing null values was that methods should not be handling null values because it clutters the code. I am a little confused with it. I have always thought that a method should always make sure that it's dependencies are not null (unless they are injected in constructor and constructor assures of nullability). For example, if I have a method

public void SendMessage(IEmailSender emailSender, contactList list)
{
    if(emailSender == null)
    {
         throw new ArgumentNullException("Failed to send  
                message.",MethodBase.GetCurrentMethod().GetParameters[0].Name);
    }
    if(list == null)
    {
         throw new ArgumentNullException("Failed to send  
                message.",MethodBase.GetCurrentMethod().GetParameters[1].Name);
    }

    // rest of code goes here

}

Am I missing something?

Edit
Report

1 Answer

1

It depends what type of code are you writing. If your public method is designed to be used by the wide range of developers non familiar with usage it makes always sense to check parameters and throw a verbose exception.

If you are writing a private method which is only used from the same class or some internal called by another friendly class also written by you or by your collaborator it makes less sense to make paranoia null checks. Your injection design and tests must ensure your internas are not getting null values.

And if private/internal method parameters still get nulls it is anyway too late. Throwing ArgumentNull exception form a private/internal method does not help external user to fix the cause, so it makes no difference for him either to get ArgumentNull or NullReference exception.

answered 2011-07-18T20:45:19.213

Your Answer