Terminally Incoherent

Utterly random, incoherent and disjointed rants and ramblings...

Sunday, April 09, 2006

The cost of elegant code...

There are essentially two ways to code:
  • Elegantly
  • Optimally

Elegant code, is usually well structured, object oriented and human readable. Blocks of code are neatly divided into meaningfully named methods. All the methods are atomic (ie. they accomplish only one clearly defined task), and encapsulation is complete. All the data is contained in meaningful data structures which have elegant accessors and mutator methods, iterators and etc... Such code is a joy to work with, and a pleasure to maintain. It also runs slow as shit flowing up the river.

Optimal code, is an ugly kludge. It is a nasty hack which lumps everything together. Method calls are computationally expensive, so the optimal code will usually consist of one method which does everything. There will be 8 different, completely unrelated things going on in a single loop (because you want to limit your iteration time). All the data is contained in arrays (preferably single dimension arrays). This code is butt ugly, but runs fast.

I am currently in the process of converting my "elegant" code to something more "optimal". The code is getting less readable and confusing by the minute. But you have to do, what you have to do.

This makes me think though - is it even possible to write "critical" code in an elegant way? We always joke about how bad coding practices introduce bugs that can be avoided. But if you are forced to optimize the shit out of your semi-elegant, program you end up shaving off allot of important stuff. Encapsulation and atomicity are the first things to go - and those are staples of OO paradigm...

Sometime bad code is necessary. This is not an excuse to write a, buggy code of course. But next time I find an ugly hackish code, I will first check if it is and optimized "speedcode" before I start complaining or refactoring.


Post a Comment

Links to this post:

Create a Link

<< Home