Tuesday, February 19, 2013

The compiler is your friend

The compiler is your friend, but only if you’re constantly aware of its presence and leverage it to its full potential. Get to know its warnings and errors – it’s trying to tell you something about your code.

A simple example is how the design of a method can be changed around to get the compiler to tell you if you’ve forgotten something.

Consider the following method that doesn’t leverage the compiler to help you:

   1:  private string BuggyMethod(bool someParameter)
   2:  {
   3:      string result = string.Empty;
   4:   
   5:      if (someParameter)
   6:      {
   7:       DoSomeWork();
   8:          result = "Some parameter was true";
   9:      }
  10:      else
  11:      {
  12:          DoSomeOtherWork(); 
  13:   // whoops - I forgot to set the result but the compiler didn't warn me!
  14:      }
  15:   
  16:      return result;
  17:  }

Now consider the following method that does the exact same thing:

   1:  private string TheCompilerHelpedMeMethod(bool someParameter)
   2:  {
   3:   
   4:      string result;
   5:   
   6:      if (someParameter)
   7:      {
   8:          DoSomeWork();
   9:          result = "Some parameter was true";
  10:      }
  11:      else
  12:      {
  13:          DoSomeOtherWork();
  14:      }
  15:   
  16:      return result; // yay... the compiler detected I forgot something!
  17:   
  18:  }
Error 1 Use of unassigned local variable 'result'
The main difference between these methods is that in the second one, you’re leveraging the compiler’s validation rules to tell you that you’ve forgot to assign the value to a variable – by omitting the initialization of the variable, you can ensure you’ve covered all branch paths in the method.

This is a trivial example, but the compiler has many more static analysis tools built right in that can help you write more robust code. Learn to make the compiler your friend.

No comments:

Post a Comment