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

Viewed 30000

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.

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?

12 Answers

Principle: Place local variable declarations as close to their first use as possible, and NOT simply at the top of a method. Consider this example:

/** Return true iff s is a blah or a blub. */
public boolean checkB(String s) {
    // Return true if s is a blah
    ... code to return true if s is a blah ... 

    // Return true if s is a blub. */
    int helpblub= s.length() + 1;
    ... rest of code to return true is s is a blah.

    return false;
}

Here, local variable helpblub is placed where it is necessary, in the code to test whether s is a blub. It is part of the code that implements "Return true is s is a blub". It makes absolutely no logical sense to put the declaration of helpblub as the first statement of the method. The poor reader would wonder, why is that variable there? What is it for?

Related