When Understanding means Refactoring

Jeff Atwood on When Understanding means Rewriting:

“It’s not that developers want to rewrite everything; it’s that very few developers are smart enough to understand code without rewriting it. And as much as I believe in the virtue of reading code, I’m convinced that the only way to get better at writing code is to write code. Lots of it. Good, bad, and everything in between. Nobody wants developers to reinvent the wheel (again), but reading about how a wheel works is a poor substitute for the experience of driving around on a few wheels of your own creation.”

When I try to understand a given piece code (most embarrassing, my own code written a few months ago), reading the code doesn’t cut it. Instead I try to nibble around on the edges, working from the inside out:
* Looks like the one who wrote the code was short on vowels & consonants for variables – Let’s try to change that – Ah, it still compiles. Cool.
* There are these two lines of code I understand – How about making that a method
* Looks like there’s a comment describing what’s done – Maybe I should try to extract a method
* There’s a certain piece of code used over and over again, maybe I can try to extract that?
* Is this method called from other places too? What do these other places feed in there as parameters?
* There’s this weird global (singleton) there, why is it needed? Let’s change its name. Ah, the compiler tells me where it’s used elsewhere in the system
* Stepping through the code in the debugger, I get a picture of the state of variables
* …
With every tiny step, I gain understanding. Little by little. After understanding this one method, I’m in better shape to understand the next one – Or even the object the method belongs to. Now I apply similar tiny baby steps to classes.
My suggestion is to refactor in order to understand the code instead of rewriting it.
Yup, backing up these refactorings with unit tests is a great idea – but I can still back out from fiddling around with the code without the tests, start the refactorings from scratch, with unit tests – but with some increased knowledge about the system.

Comments are closed.