Refactoring Day 15 : Remove Duplication

A day late on this one. Sorry about that!

This is probably one of the most used refactoring in the forms of methods that are used in more than one place. Duplication will quickly sneak up on you if you’re not careful and give in to apathy. It is often added to the codebase through laziness or a developer that is trying to produce as much code as possible, as quickly as possible. I don’t think we need anymore description so let’s look at the code.

   1: public class MedicalRecord
   2: {
   3:     public DateTime DateArchived { get; private set; }
   4:     public bool Archived { get; private set; }
   5:  
   6:     public void ArchiveRecord()
   7:     {
   8:         Archived = true;
   9:         DateArchived = DateTime.Now;
  10:     }
  11:  
  12:     public void CloseRecord()
  13:     {
  14:         Archived = true;
  15:         DateArchived = DateTime.Now;
  16:     }
  17: }

We move the duplicated code to a shared method and voila! No more duplication. Please enforce this refactoring whenever possible. It leads to much fewer bugs because you aren’t copy/pasting the bugs throughout the code.

   1: public class MedicalRecord
   2: {
   3:     public DateTime DateArchived { get; private set; }
   4:     public bool Archived { get; private set; }
   5:  
   6:     public void ArchiveRecord()
   7:     {
   8:         SwitchToArchived();
   9:     }
  10:  
  11:     public void CloseRecord()
  12:     {
  13:         SwitchToArchived();
  14:     }
  15:  
  16:     private void SwitchToArchived()
  17:     {
  18:         Archived = true;
  19:         DateArchived = DateTime.Now;
  20:     }
  21: }

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.
  • http://weblogs.asp.net/gunnarpeipman Gunnar Peipman

    There is tool called Simian (http://www.redhillconsulting.com.au/products/simian/) that you can use in your integration server to find out code duplications. This tool may greatly help you to get over-all picture of code duplications in entire project.

  • http://www.mobiusdevelopment.com John Miller

    I use duplicatefinder.codeplex.com to check for this code smell.