A simple example of how it can be easier to make a change by first refactoring the code to make the change easy.
There are various ways in which refactoring can fit into our programming workflow. One useful notion is that of Preparatory Refactoring. This is where I’m adding a new feature, and I see that the existing code is not structured in such a way that makes adding the feature easy. So first I refactor the code into the structure that makes it easy to add the feature, or as Kent Beck pithily put it ““make the change easy, then make the easy change”“.
In a recent Ruby Rogues podcast, Jessica Kerr gave a lovely metaphor for preparatory refactoring.
It’s like I want to go 100 miles east but instead of just traipsing through the woods, I’m going to drive 20 miles north to the highway and then I’m going to go 100 miles east at three times the speed I could have if I just went straight there. When people are pushing you to just go straight there, sometimes you need to say, “Wait, I need to check the map and find the quickest route.” The preparatory refactoring does that for me.
Another good metaphor I’ve come across is putting tape over electrical sockets, door frames, skirting boards and the like when painting a wall. The taping isn’t doing the painting, but by spending the time to cover things up first, the painting can be much quicker and easier.
General statements and metaphors are all very nice, but it’s good to show an example. And recently I ran into an example myself that I thought may be worth sharing.