I’m working on a VB.Net WinForms project and found myself writing code like this:
this.Fizz.Enabled = this.Buzz.Enabled = someCondition;
I couldn’t decide whether that was bad code or not. Are there any .NET guidelines for when/when-not to do assignment chaining?
2
I never do it. I always put each assignment on its own line. Clarity is king.
In practice, I seldom use enough state variables to make chaining assignments necessary. If I get to that point, I start looking for ways to trim the amount of state I am using.
1
It depends on the programming language. If you use a language where variable types are not enforced, then this could happen.
x = 1;
y = 494.0;
z = new Object();
x = y = z = "hello";
Now x,y,z are all a string. This might be confusing if found later on in the code.
The other problem is operator overloads. Some languages allow you to change what happens for the left-hand assignment of a property. So the following could happen.
x = y.something = 0;
Where y.something
doesn’t return 0
. It returns null
.
Otherwise, I don’t have a problem with it. If it’s a strongly typed language and there is no risk in the above happening. Then no problem.
The other problem is in how you read the source code.
a = b = c = new Object();
Is not the same as.
a = new Object();
b = new Object();
c = new Object();
It’s really like this.
c = new Object();
b = c;
a = b;
It might not be clear that all three variables have the same reference.
9
It’s not necessarily bad code, but it does make your code significantly less readable. Typically, I would strongly recommend against it, although I suppose there are a few cases where it might be acceptable (or merely less bad). For example, when setting a few local variables to constant value:
// accumulators
int j = 0, k = 0;
for(int i = 0; ...)
{
...
if(reset)
{
// oops we have to start from the beginning
i = j = k = 0;
}
}
In this case the line, and more importantly the comment that accompanies it, make it clear what the authors intention was when writing it. This code also contains a compound declaration which I also generally discourage, but are more acceptable here for the same reasons.
Still, I would recommend against it in most cases. There is never any harm in writing more explicit code (as long as it’s functionally identical).
4