start | find | index | login or register | edit
Montag, 13. Juli 2009 link

You're writing "production-grade" code for a large project and encounter the following problem. You have to encode (in C) a decision that somewhat naturally maps to:

(x == 0 && y == 1) ||
(x == 1 && y == 0) ||
(x == 1 && y == 1 && p)

"Naturally" means, if you consider and enumerate all valid possibilities, you'll get the above as result. (x, y are integers >= 0 and p is simply a boolean predicate, the detailed structure of which is of no interest for the remaining discussion.)

Well, after a short timespan of pondering this piece of code, you notice that it is equivalent to the following:

(x | y) == 1 && (x == 0 || y == 0 || p)

Question: which piece do you finally decide to keep?

A few more bits of information: x, y, and p are expressions but are not very expensive to compute; you are also using a compiler that is sufficiently intelligent to avoid redundant calculations of those expressions. You have to comment the chosen piece in any case and phrasing the comment to reflect the structure of the code gives a readable and easy to understand explanation for both implementations.


themel 5639 days ago:
The upper version looks like "large project code" to me with the unneeded parentheses and the nice line breaks and no delving into actual bitwise representation of the ints.

I'd say the upper code also wins for readability, since it naturally evokes "oh, a list of options" while the lower version looks like "bah, another complex condition".

Psychology experiment: Now, on your secret other blog, pose the same question, but change the order of your versions and find out if that totally reverses the answers you get.

earl 5639 days ago:
Nice idea, but, dang, if I only knew where I lost my secret other blog.

Please log in (you may want to register first) to post comments!

powered by vanilla
echo earlZstrainYat|tr ZY @.
earl.strain.at • esa3 • online for 8692 days • c'est un vanilla site