Answer the question
In order to leave comments, you need to log in
Where is it “kosher” to declare variables?
Where is the best place in the code to declare variables? I understand that this won't move the stars in the sky, but many tutorials I've seen advise declaring variables as close to where they're used as possible, while conventions say:
Put declarations only at the beginning of blocks. (A block is any code surrounded by curly
braces “{” and “}”.)
4.8.2.2 Declared when needed, initialized as soon as possible
Local variables are not habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used (within reason), to minimize their scope. Local variable declarations typically have initializers, or are initialized immediately after declaration.
Answer the question
In order to leave comments, you need to log in
If we are talking about Java, then I personally declare at the top always. So all variables are always in sight and it is easy to edit / delete unnecessary ones, instead of searching through the entire code.
Yes, this code is much easier to read.
The main thing is to stick to a single style throughout the project. I'm more used to declaring closer to use.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question