How to avoid the NULL trap?


In real life, null is nothing. However, in the programming world, null does represent the value of nothing. Basically, nothing is a value!
Still today, we see lots of code out there that contains many conditional statements that check if the value of a variable is null. This is a cause for concern in OO programming and here’s why.
Null is not an object. We might have a class, but when we have a variable with a null value we don’t have an object. Simply put, we cannot build OO code based on null references!
Therefore we need to avoid the null trap. Let’s examine the following code.

Example:

    using System; 
    namespace TestApp
     {  
       class Program  
       {    
         public static string DisplayUpperStr(string s) 
            {  
               string upper = string.Empty;  
                    if (s == null)  
               {         
            upper = null;   
              }     
            else       
          {      
               upper = s.ToUpper();
                 }     
                 return upper;  
           }   
               static void Main(string[] args)  
           {  
               Console.WriteLine(DisplayUpperStr("to upper")); 
                Console.Read();  
           } 
        } 
    } 

Syntactically, this code is perfectly ne and it produces the desired result, which is to convert to upper case a given string.
Even though this works ne, it is advisable from an OO perspective to consider constructing an object that represents nothing, rather than evaluating a condition that contains a null.
So in light of that, let’s modify the previous code as follows.

Modified Example:

 using System; 
         namespace TestApp
     { 
        class Program  
       {    
         public static string DisplayUpperStr(PossibleString s)
             {      
           string upper = s.ToPossiblyUpper();   
                   return upper;  
           }        
          static void Main(string[] args) 
            {  
               Console.WriteLine(DisplayUpperStr("to upper"));     
            Console.Read();  
           }    
     }   
  }

Notice how all of a sudden, the DisplayUpperStr function became more readable, less cluttered and it no longer uses a conditional statement to check for a null value. Much cleaner and easier to maintain.
Furthermore, the responsibility of converting the string to the upper case has moved from the calling function to the PossibleString object, specically by invoking its method ToPossiblyUpper .
Despite not having an implementation for a PossibleString class yet, we can already start to appreciate the benet that the OO paradigm provides in this example.
This leads to a separation of concerns in the code, which eventually leads to Encapsulation.



Post a Comment

0 Comments