可读性A = B = C或A = C; B = C;? [英] Readability a=b=c or a=c; b=c;?
问题描述
我有拥有一批整数的一类,说
I have a class which has a group of integers, say
foo()
{
int a;
int b;
int c;
int d;
....
string s;
}
现在的问题是最好的readbility,foo的在init()()的函数,它应该看起来像
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()
{
a=1;
b=1;
c=1;
d=1;
s = "abc";
}
原因在类的字符串是同类型的其他部门可能present和一丝当然类可能增长,因为需求变更
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
编辑:之前这个问题太过分了,这个问题的用意很简单:
在C ++有效项目12(preFER初始化在构造函数中分配),斯科特用链分配,而不是一个= C; B = C;我相信他知道什么时候该用什么,但我还记得我读还建议int类型的用书; INT B:这在分配类似的案件。在我的节目,我有一组相关的个人内建类型的类似情况需要进行初始化,我已经通过链分配发现确实使得它更容易阅读尤其是如果类有许多其他不同类型的实例变量。它似乎与我阅读的图书和我的记忆相矛盾,因此这个问题。
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.
推荐答案
我个人的preference是 A = B = C = D
,原因如下:
My personal preference is a=b=c=d
for the following reasons:
- 它简洁,节省线路
- 这传达(A / B / C / D)被初始化为的同样的事情的概念的,它们是相关
- It is concise, saves lines
- It conveys the concept that (a/b/c/d) are initialized to the same thing, that they are related
不过,需要注意的:
-
不要做,如果A / B / C / D不相关(而且恰好被初始化为1)。你会减少你的code的可读性。例如:
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;相关//美孚功能
B = D = 1;相关//酒吧功能
链接分配这样降低了未来的灵活性,为您不同的初始值赋给变量 - 因为那么你就不得不再次打破他们
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.
不过,我个人的建议是,链分配上的那些的相关的概念上的/使用的变量。在实际操作中,要改变分配的需求通常不会拿出这么经常告诫#2不应通常构成问题。
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.
编辑:我的建议可能违背公布的指南。查看评论。
My recommendation may go against published guidelines. See the comments.
这篇关于可读性A = B = C或A = C; B = C;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!