L.Zak
L.Zak

Reputation: 334

Is it good to declare a local variable in the middle level of your code?

while reading the book "clean code" I came across the following instruction:

"Local variables should be declared just above their first usage and should have a small vertical scope. We don’t want local variables declared hundreds of lines distant from their usages."

see the following example:

 public class A {

    public static void main(String[] args)  {

        String name = "Robert";
        String country = "iiiii";
        int age = 21;
        String hobby = "Soccer";
        System.out.println("my name is "+name+"I'm "+age+" and I'm from "+country);
        /*

             * 
             * a lot of code here
             * 
             * */
            System.out.println("my hobby is: " + hobby);

        }
    }

Here the variable hobby is a throw stone from its usage , so I want to make sure if it is clean to write like the code bellow?, because I often see local variables declared in the top level of the function :

/*the previous code here*/
String hobby = "Soccer";
System.out.println("my hobby is: " + hobby);

Upvotes: 0

Views: 2393

Answers (2)

Stephen C
Stephen C

Reputation: 718946

What the book is saying is correct as a general rule when we are talking about local variables.

The point it is that code tends to be a lot more readable if you keep the declaration and the usage of a variable close together. If they are far apart, you are likely to find yourself scanning backward through many lines to find the declaration. This breaks your concentration.

(Modern IDEs have clever ways to show you a variable's type, or to go to its declaration. However, it is still easier if you can just see the declaration and usage on the same "page".)

Having said that, this is a matter of personal preference to some degree. Some people like to "declare variables at the top", because some old-school programming languages do not allow declarations and other statements to be interspersed.

Upvotes: 5

SacJn
SacJn

Reputation: 777

It is actually recommended to declare a variable in least possible scope. So declare it where u use it. It just makes your code little cluttered.

Upvotes: 4

Related Questions