J
James Kanze
Sun's guidelines for Java suggest that you declare the
variables at the top of the block, even though the language
doesn't require it.
The only justification I can think of is that, like C++, Java's
syntax (like that of C++) doesn't really effectively distinguish
between a definition and an expression statement. Which makes
recognizing the definitions in a block of code somewhat
problematic. The obvious solution is to use some arbitrary
formatting element to make them identifiable---I use internal
spacing in a definition for this, for example. In Java, it's
probably not as bad defining everything at the top, since on one
hand, the only things you can define all have reasonable default
initializations which can be used if you don't know what else to
use, and the language itself requires "definite assignment": the
compiler is required to do a minimum of flow analysis in order
to verify that the variable is initialized before use. But it
still seems like a case of two wrongs trying to make a right.
Java also doesn't support inline. It helps me to think of
"setting up stack frames," rather than "declaring variables,"
even when I realize that the function I'm writing will
probably be inlined automatically, and therefore not require
its own stack frame at all.
I agree with your implied point that one probably shouldn't be
defining variables before one is ready to initialize them.
However, if you find yourself declaring variables in the
middle of a block, it may be worthwhile to factor that portion
of the block into a separate function, anyway.
Yes. Still, I can see cases where you might have a (very)
little code before defining a variable. Something like:
void*
operator new( std::size_t n )
{
n += myOverhead ;
void* result = malloc( n ) ;
// ...
}
But on the whole, if you find a lot of declarations showing up
other than at the top of the function, you're probably doing too
much in the function.