2013-05-14

Programing Craft: Intention vs Coolness

Perm URL with updates: http://xahlee.info/comp/programing_craft_intention_vs_coolness.html

When you see a hash table, do you think “Ah, it's a flow control”?

in programing, we often do coolness.

Python doesn't have {switch, case, cond} construct. Someone asked about it on stackoverflow, and this is the most upvoted answer:

# -*- coding: utf-8 -*-
# python 3

# emulating “switch” statement in Python.
# works in both python 2 and 3

def f(x):
    return {
        "a": 1,
        "b": 2,
        }.get(x, 9)    # 9 is default if x not found


# test
y = "d"
print(f(y)) # 9

you use a hash table (aka dictionary) to emulate switch statement.

It is cool, but there is a problem: the intention of the programer isn't explicit. Instead, you have to engage your brain to figure out things.

here's a simpler, more verbose, version, but the programer intention is clear, and much easier to understand.

# -*- coding: utf-8 -*-
# python 3

# chained if, similar to “switch” conditional

def f(x):
    if x == "a": return 1
    if x == "b": return 2
    return 9

y = 2

print(f(y))

Unix Shell Use of Logical Operator as Flow Control

Another example is to use logical operators for program flow control. This is most abused in unix shell, and in fact is a idiom. Here's some example from Ubuntu Linux 〔/etc/init.d/bootlogd〕:

[ -x "$DAEMON" ] || exit 0
[ "$VERBOSE" != no ] && log_end_msg $ES

They are used for flow control.

It work by a implementation quirk on evaluating boolean expressions. For example, if you have x1 || x2 || x3 || x4, as soon as “x1” is true, you don't need to evaluate the rest anymore. Similar, if you have x1 && x2 && x3 && x4, if x1 is false, the whole result is false, no need to go on.