Code Smells: Your Refactoring Cheat Codes
By Mike Farmer
April 4, 2013
Code smells are heuristics for refactoring. Resistance from our code are hints for refactoring. John Pignata shares some great tips on how to actually go about refactoring a long method. Here are some of the highlights and steps that were covered.
- Wrap entire method in a class
- Promote locals to instance variables
- Move the work into private methods
- Look for multiple responsibilities in the class
- Create new classes and adjust interfaces so everything still works
- Wrap your lower levels of abstraction (IO, Sockets).
- Your class may know too much about your lower level abstractions. Find ways to remove that knowledge using design patterns such as Observer/Listener.
- Look for case statements or other big conditionals
- Replace conditionals with polymorphism
- Move the conditional to a factory if applicable
- Remove data clumps such as knowledge of indexes in arrays or arrays of arrays (data).
- Remove uncommunicative names such as “data” and “new”
- Look for variables that have same name but different meaning such as local variables that match instance variables.
- Look for nil checks. Look for indicators that nil actually means something and replace it with a NullObject.
These are all great suggestions for refactoring. If you want more information on this topic, I highly recommend Martin Fowler’s book “Refactoring”.