Thursday, January 7, 2010

Validating Arguments

How many times have you seen (or, shame on you, written) this snippet of code to validate that an argument is not null?
public String StopDoingThis(MyRediculousObj foobar)
{
   if (null == foobar)
   {
      throw new ArgumentNullException (
      String.Format ("StopDoingThis: 'foobar' cannot be null",
      GetCallingMethod (), variable_name));
   }

   foreach (Foo foo in foobar.InfiniteFoo())
   {
      Console.WriteLine("Stop it! Please stop it!");
   }

   return "Realy, please stop it!";
}
Why do coders insist on writing this same chunk of code over and over again? I know, it's obvious: "Coders are lazy."

But if we're so lazy why then hasn't every coder from New York to Thailand encapsulated this ever so common validation. I dunno, but here it is. Use it and stop writing this damn validation at the top of every freakin' method!
public String NiceAndClean(FabulousObj sonice)
{
   ValidateNotNull("sonice", sonice)

   return "Look how nice and clean that was :)";
}

public void ValidateNotNull (
   string variable_name, Object parameter)
{
   if (null == parameter)
   {
      throw new ArgumentNullException (
      String.Format ("{0}: '{1}' cannot be null",
      GetCallingMethod (), variable_name));
   }
}

private string GetCallingMethod ()
{
   StackTrace stackTrace = new StackTrace ();

   // We get the second (2) frame.  The first frame would
   // be the method ('Method B') calling GetCallingMethod().
   // What the user really wants in the method that called
   // 'Method B', so we want the second frame.
   return stackTrace.GetFrame (2).GetMethod ().Name;
}
If you're truely a lazy coder then I'd expect you to write a whole bunch of these: ValidateNotEmpty, ValidateBounds, ValidateThisThatAndTheOtherThing. They're quicker than cut and paste, easier to read, and make your code look better than the dude in the cube next to you :p

No comments:

Post a Comment