Monday, December 22, 2014

Extract Method to eliminate duplication

ReSharper recognizes duplication when I introduce a new variable:

But not when I Extract Method.

Consider these two rules:
  • When two methods in the same class are textually identical, they are semantically identical.
Here's my recipe for eliminating duplication with Extract Method:
  1. Extract Method at each site, giving the new methods nearly-identical names ("Foo", "Foo2" is fine).

  2. Use a text diffing tool to compare the two methods, including the signature.

  3. Use automated refactoring tools to normalize (eliminate the differences). For example, rename a parameter in one method to match the other.
  4. When the two methods are textually identical, except for their names, forward one to the other.
  5. Inline the forwarding method.
This may take several attempts, and the application of other refactorings (mostly Introduce Variable and Rename) to get everything just right.

Note that you don't have to understand what the code does to make this work. You just have to see the duplication and strive to eliminate it.

I like to do fully-automated, highly-reliable refactorings instead of manual edits, where possible. Because it makes me confident that I'm not breaking anything, I can do that without test coverage, which is key to recovering legacy code.

No comments: