Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 764
Ken Avatar asked Sep 11 '09 15:09

Ken


People also ask

Should you declare variables at the top of a function?

It's best to declare variables when you first use them to ensure that they are always initialized to some valid value and that their intended use is always apparent. The alternative is typically to declare all variables in one location, typically at the top of the block or, even worse, at the top of a function.

Where should you declare variables in Java?

Declare variables as close to the first spot that you use them as possible. It's not really anything to do with efficiency, but makes your code much more readable. The closer a variable is declared to where it is used, the less scrolling/searching you have to do when reading the code later.

What is the proper way to declare a variable in Java?

Declaring (Creating) Variablestype variableName = value; Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

Where is the best place to declare variables?

The recommended practice is to put the declaration as close as possible to the first place where the variable is used. This also minimizes the scope. From Steve McConnell's "Code Complete" book: Ideally, declare and define each variable close to where it's first used.


1 Answers

Declare variables as close to the first spot that you use them as possible. It's not really anything to do with efficiency, but makes your code much more readable. The closer a variable is declared to where it is used, the less scrolling/searching you have to do when reading the code later. Declaring variables closer to the first spot they're used will also naturally narrow their scope.

like image 191
Bill the Lizard Avatar answered Sep 19 '22 22:09

Bill the Lizard