Click here to Skip to main content
Click here to Skip to main content

Extension methods to simplify null argument check

, 27 Nov 2011
Rate this:
Please Sign up or sign in to vote.
Shows how extension methods can be useful to reduce and reuse code for null argument check.

Introduction

Two rules that I like to follow while coding is 1) a method should not accept any null arguments and 2) a method should never return a null value. Following these very simple rules results in code which is simple to use more predictable and reliable. To follow rule one we always check the parameter for null value and throws ArgumentNullException if its null. This results in lot of redundant code and reduces the readability of code. I will try to improve on this by using simple extension methods. 

Regular null check  

Lets have a look at how normal null parameter check looks like.

  
public static Coffee GetCoffee(Milk milk, CoffeePowder coffeePowder, Sugar sugar)
   {
     if (milk == null)
       {
          throw new ArgumentNullException("milk", "Coffee without milk is not possible.");
       }

     if (coffeePowder == null)
       { 
          throw new ArgumentNullException("coffeePowder", "Coffee without coffeePowder is not possible.");
       }

     if (sugar == null)
       {
          throw new ArgumentNullException("sugar", "Sugarfree coffee is not supported");
       }

      // return tasty coffee as everything required is provided 
  }
 

The method is having too much of validation code which is not actually related to real implementation of the method.This certainly reduces readability of code.

Lets try Extension method

 Lets code the first extension method for object type itself. 

 

public static class Extesnion
        { 
           public static void VerifyNotNull(this Object targetObject ,string parameterName,string message)
          {
              if (targetObject == null)
              {
                  throw new ArgumentNullException(parameterName,message);
              }
          }
        } 

The method looks very simple. Lets see how it can help to reduce code size in previous example.

 public static Coffee GetCoffee(Milk milk, CoffeePowder coffeePowder, Sugar sugar)
            {     
              milk.VerifyNotNull("milk", "Coffee without milk is not possible.");
                
              coffeePowder.VerifyNotNull("coffeePowder", "Coffee without coffeePowder is not possible.");
               
              sugar.VerifyNotNull("sugar", "Sugarfree coffee is not supported");    
                
                // return tasty coffee as everything required is provided 
            }
  This extension method looks like silver bullet to me.It can be used to check null parameter of any type. It certainly helped to reduce code size and improved readability as well. But wait is it really good in all cases. No its not , because it will be accessible to all ValueTypes , since System.ValueType is also derived from ultimate base class i.e. Object. Also value types can not have null values and it is not required to check null for any of ValueType. Using this method for value types will result in boxing as well.Following code sample demonstrate the same problem.
public void Coffee[] GetCoffee(int numberOfCups)                                    
        {
          numberOfCups.VefifyNotNull("numberOfCups" , "Number of cups is not specified.")
        } 
  

   So the silver bullet should be restricted to only objects of class. Fortunately this is possible and simple to do.Let modify the extension method.
 public static void VerifyNotNull<T>(this Object targetObject, string parameterName, string message) 
                            where T : class
        {
            if (targetObject == null)
            {
                throw new ArgumentNullException(parameterName, message);
            }
        } 
 

Only thing that is required is to make the method generic and apply class constrain using where keyword.
Is it a usable now? No its not. Because there are Nullable types as well.Null check extension method should be able to check null values of Nullable types.But our extension method is only restricted to class types where as Nullable types are in fact value types which can have null values. Lets have a overload that can satisfy the need. 

 public static void VerifyNotNull<T>(this T? targetObject, string parameterName, string message)
                                 where T : struct
        {
            if (targetObject == null)
            {
                throw new ArgumentNullException(parameterName, message);
            }
        }

 So the bullet is shining now. There is some scope to improve by handling string types in better way. Usually checking only null is not sufficient for string types , as empty or string with only white space is equally unusable as null string in most cases. Lets have overload to support string differently than other types. 

public static void VerifyNotNull(this string stringTargetObj, string parameterName, string message)
      {
         if (string.IsNullOrWhiteSpace(stringTargetObj))
          {
            throw new ArgumentNullException(parameterName, message);  
          }
      }

Lets see how it look like supporting all together. 

private static Coffee GetCoffee(Milk milk, int? noOfCups, string deliveryPoint)
  {
     milk.VerifyNotNull("milk", "Coffee without milk is not possible.");

     noOfCups.VerifyNotNull("noOfCups", "Number of cups not defined.");

     deliveryPoint.VerifyNotNull("deliveryPoint", "Where to deliver the coffee cups?");
                
     //return delicious coffee     
  }   
       


  I have attached sample project for download with some extra overloads as supported by ArgumentNullExcption class.  Some unit testing is done using Nunit.

Points of Interest   

  Extension methods are definitely helpful to improved the null parameter check. Ideally I would like to have similar feature with no code solution.May be AOP can help in that case or if the compiler itself support this by means of attributes which will allow to map parameter name and exception messages in resources file. I hope this will be supported in future. Till that time I have some extension methods for rescue.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Prafulla Hunde
Software Developer CDC Sofware
India India
I am software developer with over 5 years exp.I have been working in industrial automation domain using MS technology.
I have primarily worked on winform desktop applications.
using C# with .net framework 2.0,3.5& 4.0.
I am interested and trying to get comfortable with WPF , Linq and new features..

Comments and Discussions

 
GeneralMessage Automatically Removed Pinmembermuhahahahahahaa28-Nov-11 1:03 
QuestionI find the notion offensive Pinmembermuhahahahahahaa28-Nov-11 1:02 
QuestionSystem.Diagnostics.Contracts.Contract PinmemberSergeyT227-Nov-11 7:26 
QuestionThoughts PinmemberPIEBALDconsult27-Nov-11 3:36 
Suggestionsuggestion PinmemberZoran Gelić27-Nov-11 2:44 
QuestionA Good start! PinmemberVallarasuS27-Nov-11 2:34 
QuestionMessage Automatically Removed Pingrouppaisaworld27-Nov-11 2:10 
SuggestionIf you liked this article... PinmemberPablo Aliskevicius27-Nov-11 0:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140814.1 | Last Updated 27 Nov 2011
Article Copyright 2011 by Prafulla Hunde
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid