Refactoring Day 20 : Extract Subclass


Todays refactoring comes from Martin Fowlers catalog of patterns. You can find this refactoring in his catalog here

This refactoring is useful when you have methods on a base class that are not shared amongst all classes and needs to be pushed down into it’s own class. The example I’m using here is pretty straightforward. We start out with a single class called Registration. This class handles all information related to a student registering for a course.

   1: public class Registration

   2: {

   3:     public NonRegistrationAction Action { get; set; }

   4:     public decimal RegistrationTotal { get; set; }

   5:     public string Notes { get; set; }

   6:     public string Description { get; set; }

   7:     public DateTime RegistrationDate { get; set; }

   8: }

</div> </div>

There is something that we’ve realized after working with this class. We are using it in two different contexts. The properties NonRegistrationAction and Notes are only ever used when dealing with a NonRegistration which is used to track a portion of the system that is slightly different than a normal registration. Noticing this, we can extract a subclass and move those properties down into the NonRegistration class where they more appropriately fit.

   1: public class Registration

   2: {

   3:     public decimal RegistrationTotal { get; set; }

   4:     public string Description { get; set; }

   5:     public DateTime RegistrationDate { get; set; }

   6: }

   7:  

   8: public class NonRegistration : Registration

   9: {

  10:     public NonRegistrationAction Action { get; set; }

  11:     public string Notes { get; set; }

  12: }

</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 19 : Extract Factory Class