Programing Craft: Intention vs Coolness

By Xah Lee. Date:

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 up-voted 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 what it's supposed to do.

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

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

# multiple if statement, similar to “switch” conditional

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

y = 2

print(f(y))

Note: if you have huge number of items, of course, use a hash table. However, hash table isn't a switch statement. You are no longer emulating switch statement. You are, doing hash table for whatever hash table is designed for.

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 works 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. Similarly, if you have x1 && x2 && x3 && x4, if x1 is false, the whole result is false, no need to go on.

If you have a question, put $5 at patreon and message me.