Search code examples
c#asp.netvisual-studiorefactoringcode-duplication

How to refactor code duplicated in three classes?


In Visual Studio I have a ASP.NET 4.5 project, the language is C#. In that project I have found three classes (.cs) where most of the codes are the same, including fields and properties.

In such a case, what is a good approach to minimize and integrate (refactor) the duplicate code?


Solution

  • This is a risky refactoring process, but:

    • you may want to start by writing unit tests if you don't have any

    • pick one of the classes as the master

    • rename the other ones to cause compiler errors
    • rename the classes in the client code to the master class name
    • recompile
    • add in stuff from the other two classes into the master that isn't there already
    • delete the two non-master classes

    If you have ReSharper (or some other quality refactoring tools) available this process will go more smoothly.

    Word of caution though... If you do not have unit tests set up it will be difficult to ensure that the code that looks duplicated actually is. It's easy to miss changes in logic just by visual inspection.