October 10, 2007
This is how I’ll be spending the first half of today’s workday: editing code that I wrote on Monday and Tuesday. I’d add that if you’re working in a framework that supports MVC, move the code where it belongs. It’s easy to leave bits of code that you wrote to solve an immediate problem in the wrong spot. I look at code in the views and ask, “Why shouldn’t this be in the controller or model?” Code in the controller I ask, “Why shouldn’t this be in a model?” And continue with, “Does this belong in a partial? Does that belong in a helper? Why am I doing assignment in the view?”
I start with the presumption that the code is in the wrong spot and force myself to justify its location.
Once you get a piece of code to the point where you believe it works — it’s passing its tests — go back over it and edit it. That is, go back and edit it for clarity, flow, and style. Just as if it were an essay.
This is particularly important for tests. If a test fails, it should tell a clear story that explains exactly what failed, and what it was expecting.
Things to consider editing out are vague variable or function names, and non-idiomatic shortcuts. Control flow can get tangled when working out a solution. Make it obvious. One-liners often don’t tell the full story. When you come back to a piece of code, you know the chase. It’s the first loose thread of a bug, a failed test, or an occurrence of a symbol you need to refactor. What you need is the story around it, and solid code will fill that in.
(via Daring Fireball)