In his article “Using Objects as Parameters in C#” Peter Shaw explains common problems with methods having large number of parameters and shows how to refactor those to use objects.

I would actually take that example further. Once you extract an object from parameters you may start moving behaviour, and one of the things I do first after Introducing Parameter Object is to move validation code to new object. For example, lets say that we have following business rules:

  • age has to be greater than 0
  • name and surname cannot be null neither empty

which may be expressed in the myFunction method as follow:

public void myFunction(myMethodParams theParams)
{
   if (theParams.age < 0)
      throw new ArgumentOutOfRangeException(...)
   if (String.IsNullOrEmpty(theParams.name))
      throw new ArgumentException(...)
   if (String.IsNullOrEmpty(theParams.surname))
      throw new ArgumentException(...)

After refactoring, the code will be similar to:

public void myFunction(myMethodParams theParams)
{
   if (theParams == null)
      throw new ArgumentNullException("theParams")
}

public class myMethodParams
{
   private int _age;
   private string _name;
   private string _surname;

public int age
   {
      get { return _age; }
      set
      {
         if (value < 0)
            throw new ArgumentOutOfRangeException(...);
         _age = value;
      }
   }

public string name
   {
      get { return _name; }
      set
      {
         if (String.IsNullOrEmpty(value))
            throw new ArgumentException(...);
         _name = value;
      }
   }

public string surname
   {
      get { return _surname; }
      set
      {
         if (String.IsNullOrEmpty(value))
            throw new ArgumentException(...);
         _surname = value;
      }
   }
}

This unclutters myFunction method and moves the code to the place it belong to.

See other posts in the series: