Comments are a “bad smell”  code uses to whisper “refactor me, please, I beg you.” The Problem with Comments and Coders Who Love Them is one of the top five lessons I gleaned from Martin Fowler’s Refactoring . Good comments explain why or how, not what. I love this smell. It’s got everything:
- Glamor–comments attract the eye
- Brains–comments encapsulate the solution by the very comment
- Wit–the refactoring is often simple, quick, and it’s got great ROI
I’m taking the 100 pushup challenge (I’m up to two). Here’s is your challenge, and it’s only for a week. Watch for comments as you work, and use them to identify the places code can be broken down into smaller, more discoverable chunks.
There…right there…that code you’re mucking around in? Unsure how or where to add or change that feature? Is it a long section of code with comments interspersed explaining what different sections of code do? You probably have a case for … da ta daaaa … Extract Method. The general plan is simple enough. The comment will hint at what the new method should be called, and all the code that the comment applies to will go in that new method. In a nutshell:
- Test the code (so you know later if something’s gone wrong)
- Create a new, empty method, test (yes, it really is that easy to make a bug)
- Copy the code to the new method, test. Yes, if you get interrupted, no harm done and you’ll have a good idea of where you where the next time you visit.
- Look for variables that are initialized or used elsewhere. Are they used elsewhere? Then, pass as parameters. Otherwise, localize them to the new method.
- Hm. I feel like I’m forgetting something…Oh! Right! Test!
- Replace (or comment) the code that’s been moved to the new method with a method call. I comment until after the last test.
- And, last, class? Yes, very good. Test.
If this time is hard to justify either to yourself or your muckety-muck (hey, more muck), say it’s preparing the ground for adding features. At least you’ll see whether you are in the right section of code. If so, how can the effort be wasted? If you’re in the wrong place…even better. Yes, I mean that. It saves you screwing up some code that was just minding it’s own business (refactoring doesn’t change behavior), and you’ll waste less time the next time you visit.
 “Bad smells” are patterns in code that hint, but only hint, there is something violating good coding practice.
 Refactoring is the controlled process of changing code without changing behavior so that the overall design is improved. One doesn’t open up code at random and start refactoring willy-nilly. Only a nut would want to change code just to change code. And, yes, I’ve done it, and yes, I was…well…I called myself worse than “nut.” The only reason to touch code is because something needs adding or changing. Duh.