Better Software - September 2008 - (Page 16) Code Craft Idioms and Idiosyncrasies by Pete Goodliffe Nobody wants to be a drone—well, unless you have an unhealthy fascination for bagpipes or worker bees. As programmers, we are not merely engineering drones, mechanically pushing out reams of boring, ugly code. We are also artisans. The act of programming involves as much artistry as it does technicality. Code is art. Kinda. When we craft great software, we naturally consider, perhaps subconsciously, the beauty, the elegance, and the balance of our handiwork as much as the technical correctness. We aim to create order out of chaos; we derive satisfaction from solving complex problems with designs that look so simple they cannot possibly be wrong. And we ensure that our code expresses this clearly. Or at least, we should. In every good programmer there is an internal quality meter that automatically sounds an alarm when you see code like listing 1a and that quiets down when confronted by code like listing 1b. Stop for a moment and consider the number of ways that listing 1a offends you. Count them all. How is listing 1b better? Is it any better? And what language is each one written in, anyway? bool ouch() { if (do_something() == FAILED) goto fail_1; if (do_something_else() != OK) goto fail_2; return true; fail_2: tidy_up_second_thing(); fail_1: tidy_up_first_thing(); return false; } Listing 1a: Ouch! When we’re staring at code, we like to see clear structure and code patterns with which we’re familiar. Certain code patterns are offensive—they naturally cause us to sit up, take note, and suggest extreme caution. The mere sight of a goto invokes the gag reflex. When we see messy and inconsistent layout, we feel bile rising, global variables cause an allergic reaction, and in the face of illogical and unmalleable structure, we’re gripped with the urge to run away quickly. Beauty == Idiom? Our sense of “beauty” is often shaped by familiarity—by the prevalent idioms of the implementation domain. What constitutes natural and beautiful code differs from language to int list[] = { 1, 2, 3, 5, 8 }; for (int n = 2; n < 4; n++) { do_something(list[n]); // Process 3 and 5 } Listing 2a: Idiomatic C code bool better() { try { do_something(); do_something_else(); } catch ( ) { return false; } } Listing 1b list = [1, 2, 3, 5, 8] for element in list[2:4]: do_something(element) // Process 3 and 5 Listing 2b: Equivalent idiomatic Python code list = [1, 2, 3, 5, 8] n=2 while i < 4: do_something(list[n]) n += 1 Listing 2c: Equivalent non-idiomatic Python code 16 BETTER SOFTWARE SEPTEMBER 2008 www.StickyMinds.com ISTOCKPHOTO http://www.StickyMinds.com
For optimal viewing of this digital publication, please enable JavaScript and then refresh the page. If you would like to try to load the digital publication without using Flash Player detection, please click here.