1

我有相当多的编程经验,但是多年来不断编写函数,我只是想知道社区对这件事的看法。

在函数下是声明所有变量的最佳位置是在一开始还是在你去的时候声明它们?

例如:

void fake_function1() {
    int i;
    //do something here with variable i

    int counter;
    //do something here with variable counter

 }

 or

void fake_function2() {
    int i;
    int counter;

    //do something here with variable i
    //do something here with variable counter

 }

到目前为止,我通常倾向于在 fake_function2() 中做类似的事情,因为这看起来更正确,但有时我会在 fake_function1() 中做类似的事情,因为它看起来更具可读性,并且可读代码总是更好的代码,尤其是当代码可以运行时在我看来很容易超过 100k 行。我认为一致性非常重要,但我很难决定哪个更好。

4

3 回答 3

2

一条对我真正有用的经验法则是:

声明是初始化

这意味着即使是这样int i;的陈述也要避免赞成int i = 0;

将声明的代码与处理变量的代码放在一起确实只有可维护性。

另请注意,在顶部声明变量是一种可能源于 C 不允许混合代码和声明的时间的做法。

于 2013-07-02T03:40:40.437 回答
1

The general rule for most good coding practices guides that I've seen (I've only read a few), is to declare them as close as possible to the location of first use, and to initialize them if they aren't default-constructed. This greatly reduces the chance of them being accidentally used without first being initialized, reducing the liklihood of bugs, without any increase in code or any hit to performance.

That said, I like to put local constants at the beginning of the function.

于 2013-07-02T03:32:12.540 回答
0

I understand and agree with your points and with your feeling that the second style seems more correct.

Although it may help the author of the code keep their thoughts together at first to use the style of the first function, it helps both others, and the author later on (when they return to maintain their code), if variables are declared as soon as their scope begins, which for JavaScript is at the top of the function, and for other languages is at the beginning of a block. This can seem cumbersome, but if the number of variables gets so cumbersome, then perhaps the function or blocks themselves ought to be shortened, just like good writers tend to write long sentences, but even better writers usually master the art of shortening sentences back down again.

Note well: regardless of what style is used, it is good to write code in which each variable exists only as long as necessary.

于 2013-07-02T03:34:21.923 回答