Refactoring Day 23 : Introduce Parameter Object

This refactoring comes from Fowler’s refactoring catalog and can be found here

Sometimes when working with a method that needs several parameters it becomes difficult to read the method signature because of five or more parameters being passed to the method like so:

   1: public class Registration

   2: {

   3:     public void Create(decimal amount, Student student, IEnumerable<Course> courses,

   4:         decimal credits)

   5:     {

   6:         // do work

   7:     }

   8: }

</div> </div>

In this instances it’s useful to create a class who’s only responsibility is to carry parameters into the method. This helps make the code more flexible because to add more parameters, you need only to add another field to the parameter object. Be careful to only use this refactoring when you find that you have a large number of parameters to pass to the method however as it does add several more classes to your codebase and should be kept to a minimum.

   1: public class RegistrationContext

   2: {

   3:     public decimal Amount { get; set; }

   4:     public Student Student { get; set; }

   5:     public IEnumerable<Course> Courses { get; set; }

   6:     public decimal Credits { get; set; }

   7: }


   9: public class Registration

  10: {

  11:     public void Create(RegistrationContext registrationContext)

  12:     {

  13:         // do work

  14:     }

  15: }

</div> </div>

This is part of the 31 Days of Refactoring series. For a full list of Refactorings please see the original introductory post.

Refactoring Day 22 : Break Method