CCD Red Degree Practice - Apply Simple Refactorings

Refactoring is a term that was popularised by Martin Fowler in his book Refactoring: Improving the Design of existing Code. To Refactor a piece of code you make changes to it which improve it but do not change it's external behaviour. This process can be a manual one (which is potentially dangerous) or it can be automated by a tool such as Visual Studio, Refactor Pro! or ReSharper.

In order to adhere to The Boyscout Rule you will need to make changes to the code. The best way to make these changes are to apply a series of Refactorings. This will guarantee that the code gets better but does not break. Two refactorings are recommended at the Red Degree level.

Firstly there is Extract Method. This relatively simple refactoring involves taking several lines of code and hiding them behind a method call. Ensure that the new method is named in such a way that it unambiguously can stand in for the lines of code it is replacing. This refactoring can clean up your code because it effectively raises the level of abstraction that you think at. You can often see where to apply Extract Method because someone will have several lines of code huddled under a comment. The comment is likely the name of your new method.

The second refactoring that is recommended at the Red Degree level is Rename Method. If you find a method which has a name that does not accurately reflect its actions then you should rename it. Obviously care needs to be taken when renaming public APIs.

As mentioned above you can perform these refactorings by hand but the safest way to do them is with a special purpose tool and with a suite of automated unit tests to back you up. That way you can guarantee that you haven't broken anything as you go.

The net effect of applying the above two refactorings are that you will get a lot of small methods with names that reflect exactly what they do. If done well then you will find it much easier to find (and therefore fix or modify) any particular piece of functionality in a particular class.

Posted by: Mike Minutillo
Last revised: 27 May, 2011 02:42 PM History

Comments

No comments yet. Be the first!

No new comments are allowed on this post.