Even a chimp can write code

Thursday, September 16, 2004

Good Code comes from Bad Code

If you are a proponent of code reuse, readability and maintainability, then this would be your wet dream. I was refactoring a bunch of Struts Actions on the product last week and the old bulb just lit up! Good code really does come from bad code. I started out trying to clean up some abstract classes that were crying out for help. After hours of refactoring, I was very pleased with the results. The code stench had been eliminated and we were left with works of art that looked so simple, you'd say it would have been the obvious course of action in the first place. But it wasn't.

Why didn't we think about this before, I asked myself? We took a complicated course of action when it was this simple all along. Engineers often write crappy code as stop gap measures. Because the deadlines merit a quick solution in place of a good solution. Code reviewers, maintainers and historians do not give you points for keeping deadlines. And then if you go overboard with the agile approach, foresight -- an essential element of good design and code -- doesn't keep up with the agility of code changes. If you go through short bursts of releases as we do, then cruft can be a problem too. I am referring to layers and patches added to badly designed or written code that make it difficult, if not altogether impossible, to throw the darned thing away and rewrite it all.

But I have discovered that it takes a thousand bad lines to of code to make really good code. The power to critique and deduct is almost a reflex action in most of us. In those several iterations of refactoring, I employed a number of approaches to solve the problem at hand. Most were thrown away almost as soon as Eclipse's incremental build process started churning. Others survived. In Darwinian fashion, the surviving ideas bred to form the end result. The key here is to come up with approaches, alternate approaches and alternate-to-alternate approaches. Then sit back and let the process of merciless elimination take effect.

Which brings me to some important questions. Is there really perfect code? Am I going to look at this so-called good code someday and ask myself, "What was I thinking?!" It is likely. I like to flatter myself by thinking that I too can write immortal code that lives long after I have left; after product groups have been disbanded; after companies have closed down or been bought over; unless copyright laws and dirty lawyers have resigned them to archives never to be seen again.

I love writing code and wouldn't trade it for anything else. I also love keeping deadlines.

[Acknowledgements: Thanks to Scott Berkun and Robert Watkins who've probably never heard of me, but in ways unknown to them, helped me swat some gotchas]

Email this | Bookmark this