Introduce Parameter Object

Introduce parameter object is useful when you have a set of parameters that you pass around to methods. Instead of passing all the parameters individually, you create an object that contains the parameters and then pass one object in place of all the parameters.

By introducing a parameter object, it allows you to see how data is bundled or travels in groups. This is useful because it may allow you to gain new insights into your application domain, and you may find new operations to extend the parameter object.

Simple Example

Let’s look at several methods that are defined on a class:

C#
private double AmountInvoiced(Date startDate, Date endDate) { ... }
private double AmountReceived(Date startDate, Date endDate) { ... }

It is pretty obvious that the methods are all using two dates—a start date and an end date. Here the combination is used in a few methods but even if it weren’t we may still want to introduce a parameter object. The first step is to identify what the parameter object is. A start date and an end date define a date range, so that is the parameter object. Using an appropriate construct, we define this new type:

C#
class DateRange 
{
  public Date Start { get; set; }
  public Date End { get; set; }
}

With this new parameter object in place, we then replace the individual parameters in the original methods with the new parameter object:

C#
private double AmountInvoiced(DateRange aDateRange) { ... }
private double AmountReceived(DateRange aDateRange) { ... }

Real Example

In plenty of programs you have a method that allows an id value to be updated. For example, you may pass a current id value and then the new id value:

C#
 public void InstructorStudentTransfer(int currentInstructorID, int newInstructorID) { ... }

In this code base there are several methods that all call underlying data services to update various id values. The common factor in all these methods is that they accept two int values—one for the current id and one for the new id. This is a perfect candidate for introduce parameter object.

First we need to design the parameter object. We will need a data type that has two int values—again, one for the current id and one for the new id.

C#
class IdUpdate
{
  public int Current { get; set; }
  public int New { get; set; }
}

At this point we change the original method to accept the new parameter object:

C#
public void InstructorStudentTransfer(IdUpdate instructor) { ... }

References

  1. Fowler, M. et al. Refactoring: Improving the Design of Existing Code. Pearson Education, 2012. Web. Addison-Wesley Object Technology Series.
Scroll to Top