在他的书 Effective C ++ Scott Meyers 中提出了一个有趣的指南,
In his book Effective C++ Scott Meyers brings out one interesting guideline,
项目26:尽可能地延迟变量定义。它增加程序清晰度提高程序效率。
Item 26: Postpone variable definitions as long as possible. It increases program clarity & improves program efficiency.
他提出支持上述的论点是,每当一个变量被创建或破坏,建筑& 我们可能有多个控制流,其中我们可能从函数返回,而不使用早期定义的变量(在函数的开头)&因此可能不必要地产生创建未使用的变量的成本。
The argument he puts forward to support the above is that, whenever a variable is created or destructed we incur some cost for construction & destruction of the variable. We may have multiple control flows where in we might return from the function without making use of a variable defined early(at the beginning of the function) & thus may unnecessarily incur the cost of creation of the unused variable.
这似乎是逻辑的,确实是一个好的做法。来自 c 背景我有一个趋势,在函数块的开头声明我的所有变量。也许它只是 c 背景,但我也觉得有一个函数中的一个地方的所有声明提供了方便,更好的可读性。
It all seems to be logical, & indeed a good practice. Coming from a c background I have a tendency of declaring all my variable at the beginning of a function block. Maybe it is merely the c background but I also feel having all declarations at one place in a function provides for easy & better readability.
所以问题是,你们中有多少人在日常编程中实际上遵循这样的做法,或者只是试图遵循这样的练习。
So the question is how many of you do actually follow such a practice, in day to day programming or it is merely an overkill to attempt to follow such a practice.
推荐答案我当然会。它确实需要一些适应新的习惯(从其他语言自己我知道你的意思),但一旦你在那里,它是更方便。除了您提及的内容,我还看到了2个优点:
I certainly do. It indeed takes some adaptation to the new habit (coming from other languages myself I know what you mean), but once you're there, it's much more convenient. I see 2 more benefits in addition to what you mention:
提高可读性: 缓存在大脑中记住在函数范围中使用的变量。
improved readability: you need less "cache" in your brain to remember the variables used in the function scope. Every small peace of code defines its own variables.
初始化:这是一个非常重要的原则,可能。在函数开始时并不总是可以知道初始化值
initialization: it is a very important principle that variables should be defined initialized whenever possible. It is not always possible to know the initialization value at the beginning of a function
更多推荐
如果一个敏锐&有意地尽可能长地推迟变量定义?
发布评论