javacoding-style

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);

Solution

  • 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.