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: }

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: }

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

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Sean Chambers

I am a Senior software developer from Palm Coast, Florida. An advocate of Domain Driven Design, Behavior Driven Development, creator of FluentMigrator and community activist. I am married to my beautiful wife Erin and am the proud father of two wonderful children. I currently reside at ACI, a local insurance industry/mortgage software company that excels in creating solutions using Agile methodologies.
This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.