If you don’t understand it, Refactor it


It's a Zebra Horse. Literally.

I was recently asked to implement functionality that mimic’d existing functionality in our system, but was for a different type of data.  The two types of data share a common object heirarchy, so the task was a matter of changing something that was named ‘Zebra’ to a ‘Horse’. You could even say that the only thing that differed about the two types of data was their name and the specific database objects they interacted with.

I did the naive thing at first, and I used the Copy and Paste design pattern.  I went from zero to regret in less than three keystrokes.

Copy and Paste Design Pattern

Copy and Paste is a horrible design pattern. I used it at first because it would allow me to finish the task quickly. On the other hand, I’d have to go into hiding should anyone ever stumble across that code.  The only excuse I could muster is that the code should never need to change.

About halfway through this exercise, I couldn’t shake the feeling that I still had no idea what the code actually did.  I was a monkey pulling a lever, trying to get a food pellet.

It was sickening.

The books on my shelf started to laugh at me, Clean Code, Working Effectively with Legacy Code, and Code Complete all burned in the corner of my eye not unlike the ancient Sankara stones. As I struggled to withstand their withering glare, I knew there was only one option: Roll my sleeves up and learn what the heck the code was doing, and most importantly, Refactor it.

Refactoring when you have no idea what you’re doing

The trickiest part of refactoring is how long it actually takes to figure out what a piece of code actually does. Every name, every method, every property becomes a possible source of hidden problems. Just think,  If the code was well written, there’d be no need to refactor it.

To that end, I do four things when I need to refactor code:

  1. Determine what the purpose of the code was
  2. Draw UML and action diagrams of the classes involved
  3. Shop around for the right design patterns
  4. Determine clearer names for the current classes and methods

I spend most of my time on #4.  As Mark Twain said, The difference between the almost right word & the right word is really a large matter — it’s the difference between the lightning bug and the lightning.

If you don’t understand code, play with it. Try to refactor it. Create a branch and monkey around with it. Try to improve it. Most importantly, rename it.

ZebraHorse Photo courtesy of ***Karen and her Flickr account.

Leave a Reply