Wednesday, 13 December 2006

Don't throw good code after bad code

One effective technique for writing good code is chuck out code that's not working out too well. This is probablly one of the harder techniques to get to grips with. It's pretty easy to understand the idea, however, when your actually writing code and have created a bit of a mess it is easy to convince yourself to keep tinkering to get it right. Or, alternatively, you figure you can refactor your way to good code. Usually there's something in your head that tells you that the approach your taking sucks but you know you can hack it to make it work.

Don't. Cut your losses and kill the code.

The fact you realise that it sucks means you probablly understand the problem a lot better than when you first started. Thats the key thing, that's actually the hard part, writing code when you know exactly what it has to do is often reasonably trvial once your confident in a particular language.

You might salvage the unit tests, but sometimes its better to biff those out also. This gives you the chance to rethink your approach afresh.

For starters you might just comment out your code "just in case". This is especially true if the code you have generated is quite complex. Your not quite sure if you can recreate it. However this is often a big stinky code smell and most often you will find a simpler soloution when you do it again. So once you get used to backing out of code then you'll just delete it.


Alex James said...

This one got me thinking... good stuff Keith keep it up...

Dave Nicolette said...

One thing that can make it easier to go ahead and "chunk" code is to use a version control system. When you catch yourself commenting a large swath of code, consider cleaning things up to the point that you can synchronize and check in, and then just delete the questionable code. If you later find out that you need the code back, you can restore it from the version control system. That way you can make experimental changes without cluttering up the code with commented-out bits. If you're talking about a multi-step refactoring, then version control is all the more useful because you can re-test and check in as many times as necessary to keep yourself on track, and you always have a safety valve if you need it.

Keith said...

yeah, I agree, though the problem is not all source control allows you to do this kind of stuff easily.

There's two tools I'm keeping my eye on that look really promising... (done in haskell interestingly enough)


They allow for a much more flexible way to work with share source.

also check out