Feeling the Refactoring

   By chris on March 28th 2007 in /dev/random | 316 views

We developers don’t talk much about our feelings and the rest of the world would think us crazy to talk about “feeling” software development but that’s just what I’m going to do here. I suspect if you’re the sort who reads blogs about software development you’re the sort who’ll get what I’m going for.

code_migration1Lately I’ve gotten into the habit of spending a good chunk of my coding time forcing myself to forget all the new features I want to add, ignoring the bugs that already exist and instead simply going back into existing code and refactoring it mercilessly.

I’ve noticed that when I visualize the code in my Rails app it tends to take on specific shapes. Initially it starts out like the image on the left: top-heavy, all upper-body and no legs, kind’a like a sport climber or a swimmer. Views start out fully-loaded with HTML and CSS and Ruby embedded in them. Controllers are fatter than they should be, containing too much low-level functionality and knowing too much about their models. And the models tend to be svelt little things, practically sticks.

A good refactoring later its usually possible to strip almost all the Ruby code from the views, save for basic iterative functions and output statements. At this point the bloats migrates southward and the controller ends up too fat. The structure of the code now resembles a pear-shaped, middle-aged bank manager, still with sticks for legs.

code_migration2Some more refactoring and the code shape starts to look like the image on the right, all hour-glassy and sexy. The view is all-natural HTML and CSS, the controller has been slimmed down to the very basics it needs to manage V-M interaction, and almost all the real heavy lifting has been compartmentalized and moved into the models where it belongs.

It is at this stage that the code starts to “feel” right to me. It feels like I can leave it alone, secure in the knowledge that if I have to come back to it later I’ll be able to understand it. That if I need to extend it I can be fairly confident of doing so without causing any destructive worm-hole effects. It it here that the code starts to feels good.

And that feeling is what makes refactoring so incredibly satisfying, often even moreso that writing the original code in the first place.

Feel the refactor.

Trackback URI | Comments RSS

Leave a Reply