[bind10-dev] [bikeshed] "variable == value" vs "value == variable"

JINMEI Tatuya / 神明達哉 jinmei at isc.org
Thu Mar 22 18:10:38 UTC 2012

In review of recent tickets I've noticed some developers seem to
prefer this style:
(Style A)
   int x;
   if (10 == x) {
       // then do something that has to be done when x is 10

I'd propose we write instead
(Style B)
   int x;
   if (x == 10) {
       // then do something that has to be done when x is 10

and add it to our style guideline.

My reason for the suggestion is readability and style consistency.

Regarding readability, Style A reads quite awkward to me.  Style B can
naturally be understood as "If x is equal to 10, then...", but Style
A requires some transformation inside your brain from a C/C++
expression to the human-understandable semantics.

In my understanding, the only benefit of Style A is that it could be
more robust against a typo like "10 = x" (which is a syntax error and
can be detected at compile time, while "x = 10" is a valid
expression).  But I'd say this defence doesn't outweigh degrading the
readability in the world with modern compiler/language.  Modern
compilers generally warn if we omit one '=' in style B:

foo.cc:18: warning: suggest parentheses around assignment used as truth value

(with some higher level of warning options), and with something like
-Werror we can still detect it at compile time.

Also, in C++ many more variables can (and should) be const, and if the
variable is const we can even detect the typo at compile time based on
the language specification.  If variable x in Style B is const and we
omit '=' in the if condition, we'll see something like this:

error: assignment of read-only variable 'x'

In my opinion, we should rely on computers and compilers (and
sometimes the power of language rules) for avoiding and detecting
human errors like this, rather than by introducing less understandable

As for consistency, this is probably minor compared to inconsistency
on (e.g.) the indentation width.  But to me the mixture of these two
styles still imposes the impression that the code isn't well
maintained, allowing arbitrary changes to be introduced.  So at the
very least I'd like to use (only) either of the styles consistently -
although I strongly prefer Style B, if the majority of the developers
insist Style A is better, I'd rather suggest using that style
throughout our code.

JINMEI, Tatuya

More information about the bind10-dev mailing list