I have a class which has a group of integers, say
foo()
{
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";
}
or
void init()
{
a=1;
b=1;
c=1;
d=1;
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.
I happen to prefer the chained version, but it's completely a matter of preference.
Please note, however, that
a = b = c = 0;
is equivalent to:
c = 0; b = c; a = b;
and not
a = 0; b = 0; c = 0;
(not that it should matter to you which assignment happens first)
My personal preference is a=b=c=d
for the following reasons:
However, caveat:
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
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.
I guess it is a matter of opinion which is most readable. (Clearly so ... otherwise you wouldn't be asking.)
However Oracle's "Code Conventions for the Java TM Programming Language" clearly says to use separate assignment statements:
10.4 Variable Assignments. "Avoid assigning several variables to the same value in a single statement. It is hard to read."
My opinion?
1 ... or get out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With