Yuan Yuan - 3 years ago 328
C# Question

Readability a=b=c or a=c; b=c;?

I have a class which has a group of integers, say

int a;
int b;
int c;
int d;
string s;

Now the question is for the best readbility, the init() function for foo(), should it look like

void init()
a=b=c=d=1; //for some reason they are init to 1;
s = "abc";


void init()
s = "abc";


The reason for a string in class is a hint of other groups of same types might present and of course, the class might grow as requirement changes

EDIT: before this question goes too far, the intention of this question was simple:
In Effective C++ item 12 (prefer initialization to assignment in constructors), Scott uses chain assignment instead of a=c; b=c; I am sure he knows when to use what, but I also remembered the books I read also recommended to use int a; int b; which in similar case of assignments. In my program I have a similar situation of a group of related individual build-in types needs to be initialized and I have found by making a chain assignment does makes it easier to read especially if the class have many other different types instance variables. It seems to contradict with books I read and my memory, hence the question.

Answer Source

My personal preference is a=b=c=d for the following reasons:

  1. It is concise, saves lines
  2. It conveys the concept that (a/b/c/d) are initialized to the same thing, that they are related

However, caveat:

  1. Don't do that if a/b/c/d are not related (and just happens to be initialized to 1). You'll reduce the readability of your code. Example:

    a=c=1; // Foo-function related

    b=d=1; // Bar-function related

  2. Chaining assignments like this reduces the flexibility for you in the future to assign different initial values to the variables -- because then you'll have to break them up again.

Nevertheless, my personal recommendation is to chain assignments on variables that are related on concept/usage. In actual practice, the need to change an assignment usually doesn't come up often so caveat #2 should not typically pose a problem.

Edit: My recommendation may go against published guidelines. See the comments.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download