Checking your in parms.

Working with several customers over time I come across a common coding practices (note I did not say best practice), that I promised I would one day start blogging about.  I have seen in many scenarios where developers are just doing too much work when checking for valid input parameters, especially in distributed (unattended) components.  If the parm is invalid throw an exception and stop processing.  The burden is on the caller to make sure they pass the server component valid data.  It is not your job to clean up the client mess, if you are passed bad or unexpected data.

Scenario for today:  You are developing an application and one of your distributed (server side) components needs to check it's in params to make sure they are valid.  Well let me start by first of all commending you on checking your input parameters for validity before executing code assuming they are valid.  However there are some improvements to be realized in some of the code I seen out in the wild.

Here is a common example I have come across many times:

void ClientSideMethod()

{

  myObject.ExecuteServerMethod(null, 0, 0);

}

ExecuteServerMethod(string[] parm1, int parm3, double parm3)

{

  If (parm1 != null)

  {

    If (parm1.Length > 0)

    {

        // do business logic here …

     }

   }

}

As a the server side developer your life is easy, all you have to do is tell the client they sent you bad data and abort the function in this scenario. Consider the revised server side code.

ExecuteServerMethod(string[] parm1, int parm3, double parm3)

{

  If (parm1 == null)

    throw new ArgumentNullException(“parm1 cannot be null”);

  If (parm1.Length > 0)

  {

  // do business logic here …

  }

}

All you are responsible for at this stage is validating you have good input. If you do not then you can get away with throwing the client an exception and forcing them to call your function correctly.

I hope this helps some of the development I have seen where there are lots of nested if/then blocks to validate input.

Happy coding…