I’ve been reading Refactoring and two things have gotten my gears turning.
Thing one: refactoring moves understanding from your head back into your code. When you finally grok how something is working, refactor the code to make that understanding obvious.
Read the code, gain some insight, and use refactoring to move that insight from your head back into the code. The clearer code then makes it easier to understand it, leading to deeper insights and a beneficial positive feedback loop.Martin Fowler
For example, if you realize that a chunk of code is determining the pricing for a soccer match, extract that into a
determinePrice() function so that next time it’ll be obvious.
Or if discover two different types of Articles (Text and Video), make
VideoArticle classes that extend the
Article class. That way, no one will ever need to learn that lesson the hard way again.
Whenever you think “ah, so that’s what this is doing” use that as a mental trigger that you should refactor to make it self evident.
It’s embarrassing how obvious this seems in retrospect. I’ve used that as a trigger to write documentation or do some knowledge sharing, rather than improve the code.
Thing two: refactoring should be done in tiny steps, and the code should never be in a broken state. You make a little change, compile-test-commit, and repeat. The changes will be small, but they add up.
Whenever I’ve shown people how I refactor, they are surprised by how small my steps are, each step leaving the code in a working state that compiles and passes its tests. The key to effective refactoring is recognizing that you go faster when you take tiny steps, the code is never broken, and you can compose those small steps into substantial changes.Martin Fowler
I never realized that I could change so much without breaking stuff in the process. I always assumed refactoring was the code equivalent of cracking eggs to make an omelette.
Last week, I spent a couple hours moving code around and creating classes and changing method definitions. Then I spent the next 4 hours trying to make it all work again. Oh how I wish I had read this book before that.
Important note: this depends on having solid and fast automated tests. Writing tests is often the first step of refactoring. Remember, you should compile-test-commit after each change. That’s going to be brutal if you can’t make robots do your testing for you.
I’m not even halfway through Refactoring but so far it’s fantastic. Have you read it? What did you think? Tweet me and let me know.