October 29, 2007

Few pointers on refactoring


If refactoring isn’t a part of your daily life you may find it a bit hard to know what to do. There is also that fear of messing up code that is working properly. Well, the later can be eased by having extensive test coverage. The more tests the codebase has the safer the refactoring will be. And for the former I tried to put a few pointers here. This isn’t a complete list of refactorings though, it is just a start.
  • Read the class and try to understand it.
  • Is the class responsibility clear? Or is the class doing more than it should?
  • Are there fields been accessed directly by other classes. If yes encapsulate.
  • Do the public methods have meaningful names? Are they aligned with the class’ responsibility? If not extract to Helper class.
  • Check if public methods really need to be public. Always Ctrl+Shift+G to see who’s referencing it.
  • Mind visibility modifiers. Ensure you have a reason when using public, protected or default.
  • Is the class been instantiated in more than one place and does it have subclasses? Considerer extracting an interface.
  • Duplicated (or very similar) code? Extract a method. Rule of thumb: DON’T Ctrl+C, Ctrl+V as it leads to Code Horror ™.
  • Do private methods contain class specific or do they look like a util-type of code? If yes move it to a proper class.
  • Util classes are singletons or static methods, we shouldn’t need to instantiate utilities.
  • Extract methods from the if’s conditional clause, body, and else parts. Avoid complicated ifs and elses as they usually clog the code and create unnecessary duplication. Think about using Strategy.
  • Check for extends. Can I compose instead of inherit?
  • When using methods from different interfaces in a complementary way consider writing a Fa├žade to join the two (or more) of them
  • Don’t wait for a NullPointer to explode the stacktrace, use Assert.

No comments:

Post a Comment