Re:When to refactor code
by loup-vaillant on Thursday May 16, 2013 @02:15PM
(#5720080)
Aand, while where at it, minimize the side effects. Avoid methods that modify objects, replace them by equivalent methods that create new objects. Likewise, expunge init() methods. Their code belong to constructors, factories, or curried functions. Basically, avoid the assignment statement: http://loup-vaillant.fr/tutorials/avoid-assignment
This is especially crucial when you break up your code in a myriad of small functions/methods: the whole point of refactoring was to make them readable, which means small and self contained —you don't want to keep a gazillion dependencies in mind while reading and testing a given method. Avoiding side effects is a big help there, because it will make your interfaces more explicit, and your dependencies more visible.
Anyway, I don't think you need a big, complicated checklist like this. Writing code by checklist is not going to solve your problems. The more important questions are these:
- Do you find yourself spending more time than you think you should making changes and additions (or bug fixes) to the same sections of code?
- Do you often run into difficulty figuring out or remembering what a given section of code does?
If either of those things are true then refactoring might be a good idea. Use extract method until it hurts. Use extract method on complicated logic tests as well. Figure out where the control flow is wonky and switch to using flow based on method calls and returns to simplify things. Be ruthless. Don't be lulled into the "meaty method" trap, don't be afraid of short methods, even if they're only one line. Make your code so that it looks almost too simple, as though even a novice could look at it and tell you what it does. Push until you get to a state where making changes seems almost like cheating because it's so easy. That's when you know you're in the sweet spot. Programming is about making things easier, even future programming, not about proving how incredibly skilled you are at maintaining complex code.