T
T
Tarasov Konstantin2014-07-04 14:49:12
Java
Tarasov Konstantin, 2014-07-04 14:49:12

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 “}”.)

Z.Y. At the same time, Google Java Style, which is also sometimes referred to, says the opposite:
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

4 answer(s)
I
Ilya Kaznacheev, 2014-07-04
@Color

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.

T
tsarevfs, 2014-07-04
@tsarevfs

The main thing is to stick to a single style throughout the project. I'm more used to declaring closer to use.

P
Puma Thailand, 2014-07-04
@opium

I think the same is written

J
javanub, 2014-07-08
@javanub

For example, you can't write like this:

int i;
for(i = 0; i < 10; i++)
....

Do :
Or like this:
int i;
public void setDescr(){
i = 23;
System.out.println(i);
}

Necessary:
public void setDescr(){
int i = 23;
System.out.println(i);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question