在 Java 中,变量应该在函数顶部声明,还是在需要时声明?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1411463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:48:25  来源:igfitidea点击:

In Java, should variables be declared at the top of a function, or as they're needed?

javasyntaxvariablescoding-style

提问by Ken

I'm cleaning up Java code for someone who starts their functions by declaring all variables up top, and initializing them to null/0/whatever, as opposed to declaring them as they're needed later on.

我正在为那些通过在顶部声明所有变量并将它们初始化为 null/0/whatever 来启动其函数的人清理 Java 代码,而不是在以后需要时声明它们。

What are the specific guidelines for this? Are there optimization reasons for one way or the other, or is one way just good practice? Are there any cases where it's acceptable to deviate from whatever the proper way of doing it is?

这方面的具体指导方针是什么?是否有一种或另一种方式的优化原因,或者一种方式只是一种好的做法?是否有任何情况下偏离正确的做法是可以接受的?

回答by Bill the Lizard

Declare variables as close to the first spot that you use them as possible. It's not really anything to do with efficiency, but makes your code much more readable. The closer a variable is declared to where it is used, the less scrolling/searching you have to do when reading the code later. Declaring variables closer to the first spot they're used will also naturally narrow their scope.

在尽可能靠近您使用它们的第一个位置声明变量。这与效率没有任何关系,但会使您的代码更具可读性。变量声明的位置越接近它的使用位置,稍后阅读代码时所需的滚动/搜索就越少。在更接近它们使用的第一个位置声明变量也会自然地缩小它们的范围

回答by S.Lott

If you have a kabillion variables used in various isolated places down inside the body of a function, your function is too big.

如果您在函数体内部的各个隔离位置使用了 kabillion 变量,则您的函数太大了。

If your function is a comfortably understandable size, there's no difference between "all up front" and "just as needed".

如果您的函数是一个易于理解的大小,那么“全部预先”和“按需”之间没有区别。

The only not-up-front variable would be in the body of a forstatement.

唯一的非预先变量将在for语句的主体中。

for( Iterator i= someObject.iterator(); i.hasNext(); ) 

回答by James Schek

I've found that declaring them as-needed results in fewer mistakes than declaring them at the beginning. I've also found that declaring them at the minimum scope possible to also prevent mistakes.

我发现根据需要声明它们比在开始时声明它们会导致更少的错误。我还发现在尽可能小的范围内声明它们也可以防止错误。

When I looked at the byte-code generated by the location of the declaration few years ago, I found they were more-or-less identical. There were ocassionally differences depending on when they were assigned. Even something like:

几年前,当我查看由声明位置生成的字节码时,我发现它们或多或少是相同的。偶尔会有差异,具体取决于他们被分配的时间。甚至像:

for(Object o : list) {
   Object temp = ...;  //was not "redeclared" every loop iteration
}

vs

对比

Object temp;
for(Object o : list) {
   temp = ...; //nearly identical bytecoode, if not exactly identical.
}

Came out more or less identical

出来或多或少相同

回答by Vincent Ramdhanie

Its a matter of readability and personal preference rather than performance. The compiler does not care and will generate the same code anyway.

它是一个可读性和个人喜好而不是性能问题。编译器不在乎,无论如何都会生成相同的代码。

回答by pave

I've seen people declare at the top and at the bottom of functions. I prefer the top, where I can see them quickly. It's a matter of choice and preference.

我见过人们在函数的顶部和底部声明。我更喜欢顶部,在那里我可以快速看到它们。这是一个选择和偏好的问题。

回答by Tim

From the Java Code Conventions, Chapter 6 on Declarations:

来自Java 代码约定关于声明的第 6 章

6.3 Placement

Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

void myMethod() {
    int int1 = 0;         // beginning of method block

    if (condition) {
        int int2 = 0;     // beginning of "if" block
        ...
    }
}

The one exception to the rule is indexes of for loops, which in Java can be declared in the for statement:

for (int i = 0; i < maxLoops; i++) { ... }

Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:

int count;
...
myMethod() {
    if (condition) {
        int count = 0;     // AVOID!
        ...
    }
    ...
}

6.3 安置

仅将声明放在块的开头。(块是由大括号“{”和“}”包围的任何代码。)不要等到第一次使用时才声明变量;它可以混淆粗心的程序员并妨碍范围内的代码可移植性。

void myMethod() {
    int int1 = 0;         // beginning of method block

    if (condition) {
        int int2 = 0;     // beginning of "if" block
        ...
    }
}

该规则的一个例外是 for 循环的索引,在 Java 中可以在 for 语句中声明:

for (int i = 0; i < maxLoops; i++) { ... }

避免在更高级别隐藏声明的本地声明。例如,不要在内部块中声明相同的变量名:

int count;
...
myMethod() {
    if (condition) {
        int count = 0;     // AVOID!
        ...
    }
    ...
}

回答by Michael Borgwardt

The proper way is to declare variables exactly when they are first used and minimize their scope in order to make the code easier to understand.

正确的方法是在变量第一次使用时准确地声明变量并最小化它们的范围,以使代码更容易理解。

Declaring variables at the top of functions is a holdover from C (where it was required), and has absolutely no advantages (variable scope exists only in the source code, in the byte code all local variables exist in sequence on the stack anyway). Just don't do it, ever.

在函数顶部声明变量是 C 的保留(需要它),并且绝对没有优势(变量范围仅存在于源代码中,在字节码中,无论如何所有局部变量都按顺序存在于堆栈中)。永远不要这样做。

Some people may try to defend the practice by claiming that it is "neater", but any need to "organize" code within a method is usually a strong indication that the method is simply too long.

有些人可能会通过声称它“更整洁”来为这种做法辩护,但是在方法中“组织”代码的任何需要通常都强烈表明该方法太长了。

回答by Jeremy Cron

I am doing this very same thing at the moment. All of the variables in the code that I am reworking are declared at the top of the function. I've seen as I've been looking through this that several variables are declared but NEVER used or they are declared and operations are being done with them (ie parsing a Stringand then setting a Calendarobject with the date/time values from the string) but then the resulting Calendarobject is NEVER used.

我目前正在做同样的事情。我正在修改的代码中的所有变量都在函数顶部声明。我已经看到,因为我一直在查看这个,声明了几个变量但从未使用过,或者声明了它们并且正在使用它们完成操作(即解析 aString然后Calendar使用字符串中的日期/时间值设置一个对象)但随后生成的Calendar对象从未使用过。

I am going through and cleaning these up by taking the declarations from the top and moving them down in the function to a spot closer to where it is used.

我正在通过从顶部获取声明并将它们在函数中向下移动到更接近使用它的位置来检查和清理这些。

回答by Ants Aasma

Defining variable in a wider scope than needed hinders understandability quite a bit. Limited scope signals that this variable has meaning for only this small block of code and you can not think about when reading further. This is a pretty important issue because of the tiny short-term working memory that the brain has (it said that on average you can keep track of only 7 things). One less thing to keep track of is significant.

在比所需范围更广的范围内定义变量会极大地阻碍可理解性。有限的范围表明这个变量只对这个小代码块有意义,你在进一步阅读时无法考虑。这是一个非常重要的问题,因为大脑的短期工作记忆很小(它说平均你只能跟踪 7 件事)。要跟踪的少一件事很重要。

Similarly you really should try to avoid variables in the literal sense. Try to assign all things once, and declare them final so this is known to the reader. Not having to keep track whether something changes or not really cuts the cognitive load.

同样,您确实应该尝试避免字面意义上的变量。尝试将所有内容分配一次,并将它们声明为 final,以便读者知道。不必跟踪某些事情是否发生了变化,从而真正减轻了认知负担。

回答by soru

I think it is actually objectively provable that the declare-at-the-top style is more error-prone.

我认为实际上可以客观地证明,顶部声明样式更容易出错。

If you mutate-test code in either style by moving lines around at random (to simulate a merge gone bad or someone unthinkingly cut+pasting), then the declare-at-the-top style has a greater chance of compiling while functionally wrong.

如果您通过随机移动行来改变任一风格的测试代码(以模拟合并变坏或有人不加思索地剪切+粘贴),则声明在顶部样式在功能错误时编译的可能性更大。

I don't think declare-at-the-top has any corresponding advantage that doesn't come down to personal preference.

我不认为在顶部声明有任何不归结为个人偏好的相应优势。

So assuming you want to write reliable code, learn to prefer doing just-in-time declaration.

因此,假设您想编写可靠的代码,请学会更喜欢进行即时声明。