Sometimes I run into a situation where I need to equate two new variables with an old one. Which of the following (if any) is a good practice (w.r.t. code readability or any other factor), under what conditions?
a=b;
c=b;
or
a=b;
c=a;
Note, a
,b
and c
are just the names chosen in this example.
3
Humans are Parsers Too! Encourage Maximum Readability!
Given your 2 choices, I’d favor the first one:
a = b;
c = b;
It’s easier to visually parse and to figure out that both a
and c
now have the same value as b
. Or at least you quickly see that 2 separate things get the same value.
In the second example, none of this is immediately obvious.
Discourage Ambiguity
I’d also discourage one-liners (a = b = c;
) for similar reasons, and because they hide multiple expressions in a single statement. This facilitates the introduction of fly-by errors* and leads to developing a (bad) habit of cramming too much in too little space for a false sense of expressiveness.
* For instance, I’ve often come across things like:
a = b = b;
(when obviously ac
was intended somewhere),- and then quickly you’ll see things like
if (a == (b = c)) {}
… and now you’re one typo away fromif (a = (b = c))
and then you’ve got absolutely no clue what the intended behavior was. Ah, and use descriptive variable names, obviously.
2
If the language allows for this syntax (and most do), I’d highly prefer this:
a = c = b;
I’d be inclined to agree with deceze. Yes, this example is clear(ish):
a = b;
c = b;
But introduce more variables and it just becomes horrible:
a = z;
b = z;
c = z;
.
.
.
w = z;
x = z;
y = z;
At which point would you draw the line and go for the single assignment statement? 3 variables? 4? 5?
Setting some arbitrary limit would seem to be daft (and in contravention of the Zero One Infinity Rule).
5