"Don't wait to declare variables until their first use..."
I completely agree for MOST methods, Naah, I don't agree with this standard at all. Swing code is a good example of the ugliest effects of this dictum, but I think it's pretty pointless in general. The Book of Joshua, Chapter 7, Item 29: Minimize the scope of local variables.
The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used. If a variable is declared before it is used, it is just clutter - one more thing to distract the reader who is trying to figure out what the program does. By the time the variable is used, the reader might not remember the variable's type or initial value. If the program evolves and the variable is no longer used, it is easy to forget to remove the declaration if it's far removed from the point of first use.
I agree, and further I have a strong preference for short methods wherever possible; I like to be able to see the entirely of a method on my screen at once, without needin to scroll about. Declare-before-use interferes with this.
But, Sun's coding standard is unfortunately clear here. (Though I could argue that Effective
Java is at least as indicative of Sun's recommended practices as the coding standard is, but I guess I won't.) So, comply with the standard, however ugly it may be.
However there are ways to minimize the ugliness. Note that you're required to declare at the beginning of a
block, not necessarily the beginning of a
method. If a variable is only needed inside a for loop, you can still declare it at the beginning of the loop. And you're allowed (encouraged even) to initialize during the declaration - you can accomplish quite a lot here if you call another method in the initialization. And I will often move work to other methods Here's an example of the sort of thing I sometimes do for swing:
I don't mind having lots of (private) methods if they have decent self-descriptive names - I just want the individual methods to be simple and easily understood. Lots of people have GUI setup methods taking hundreds of lines, which gets even worse if you're required to declare before use. The structure above allows me to avoid that. Dunno it anyone else likes it, but it works for me, and seems to comply with the coding standards.