Give life to parameter objects (part 2)

Mariusz Wojcik

In the previous post I wrote about my usual second step in refactoring to Parameter Object – moving related validation code. This is really easy to do and greatly de-clutters the method. Now it is a time to scrutinise code more and move behaviour which belongs to our new parameter object.

The first suspects on my list are various conditional statement which operate on parameters, like in the below example:

public void myFunction(myMethodParams theParams)
{
   // ...
   if (age < 18)
   {
      // case for minors
   } else {
      // case for grown-ups
   }
}

The condition in line 5 is a perfect candidate for refactoring. We can move the logic into myMethodParams class and give it a nice, meaningful name:

public bool IsUnderage
{
   get { return age < 18; }
}

This works even nicer for conditions based on more than one boolean expression.

Another candidates are operations on data. For example, lets assume that at some point we need a full name. Instead of keeping the operation scattered in the code we should move it to a property of myMethodParams class:

public string FullName { get { return String.Concat(_name, " ", _surname); }

Summary

Moving behaviour to the object gives us a chance to pick nice meaningful name for it, make the code cleaner and easier to understand. Very often it also helps to remove code duplication. Step by step the parameter object transforms into a business object which describes Person. From the experience I noticed that applying those refactorings help people making the first step into OOP. It allows to understand that application doesn’t have to live in the main function. That domain objects have both – data and behaviour, and the application is an interaction of those objects.

See other posts in the series: