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

前端 未结 12 1429
猫巷女王i
猫巷女王i 2020-12-02 13:09

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 a

12条回答
  •  盖世英雄少女心
    2020-12-02 13:39

    From the Java Code Conventions, Chapter 6 on Declarations:

    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!
            ...
        }
        ...
    }
    

提交回复
热议问题