8 Replies Latest reply: Oct 11, 2012 3:03 PM by aksarben RSS

    Best Practice in defining variables

    SRAVZ
      Hi All

      What is the best practice to use variables inside a method and any specific advantage .i.e. initializing variables starting of the method vs defining them where they are required.

      public String abc(){
      int i = 0;
      String s = null;
      i = 10 + 50;
      s = "Java" + "world";
      return s;
      }

      vs

      public String abc(){
      int i = 10 + 50;
      String s = "Java" + "world";
      return s;
      }
        • 1. Re: Best Practice in defining variables
          abillconsl
          Generally you will want to declare it closest to, or where, it is first used. And try to avoid String concatonation - String s = "Javaworld" is better.
          • 2. Re: Best Practice in defining variables
            rp0428
            >
            What is the best practice to use variables inside a method and any specific advantage .i.e. initializing variables starting of the method vs defining them where they are required.
            >
            Whereever they are declared within a method they become part of the stack frame that is created when the method is called and the 'disappear' when that stack frame is destroyed when the method returns.

            You should declare variables WITHIN the scope that they are used in.

            Variables declared at the start of the method are visible everywhere in the method unless they are hidden by a variable of the same name that has its own scope.

            So if you need a variable (e.g. 'i') in a FOR loop you should declare it as part of the FOR statement and not at the beginning of the method.
            • 3. Re: Best Practice in defining variables
              SRAVZ
              so can you give me an recommendation with an example.....?
              • 4. Re: Best Practice in defining variables
                rp0428
                >
                so can you give me an recommendation with an example.....?
                >
                Using your examples instead of
                public String abc(){
                int i = 0;
                String s = null;
                i = 10 + 50;
                s = "Java" + "world";
                return s;
                
                vs
                
                public String abc(){
                int i = 10 + 50;
                String s = "Java" + "world";
                return s;
                } 
                For 'i' the second example is better. No need to init 'i' to 0 if you aren't going to use it.

                But if you are just returning a string you don't need 's' at all. Just return "Javaworld";
                • 5. Re: Best Practice in defining variables
                  SRAVZ
                  So can i say my second example is better?
                  • 6. Re: Best Practice in defining variables
                    DrClap
                    You can say that if you like, but "not as bad" would be a better description.

                    The general rule you were fishing for has nothing really to do with variables, it's "Don't write unnecessary code". And even your second example has unnecessary code -- it assigns a value to an int variable which is never used, and it assigns a value to a String variable and then immediately returns that variable. It could just have returned the value directly.
                    • 7. Re: Best Practice in defining variables
                      TPD-Opitz
                      SRAVZ wrote:
                      What is the best practice to use variables inside a method and any specific advantage .i.e. initializing variables starting of the method vs defining them where they are required.
                      As the others wrote the later is preferred. One reason is that this can save memory.

                      Another (IMHO) important reason is that it eases the use of refactorings provided by your IDE.
                      Look at this code:
                      public int testRefactoring() {
                                int result = 0, factor = 0;
                                RefactoringTest rt = new RefactoringTest();     
                                result = rt.getA();
                                factor *=result ;
                                result= factor;
                                result += rt.getB();
                                return result;
                           }
                      As you may see the calculation of the result uses only values from the class <tt>RefactoringTest</tt> so it should be placed there. This is no problem since almost any IDE can do this in 2 steps:<ol><li>extract method</li><li>move method (to one of its parameters)</li></ol>Lets start with the first step: <ul><li>select lines 4 to 7 </li><li> hit "shift+alt+m" (in eclipse),</li><li> enter a name for the new method </li><li> click OK.</li></ul>
                      The result is a method with 3 Parameters. Two of them are useless.

                      If you'd switch line 2 and 3 you could include the variable declaration in your selection thus leading to a method with one parameter only...

                      bye
                      TPD
                      • 8. Re: Best Practice in defining variables
                        aksarben
                        Another reason for declaring variables as late as possible: If you declare them earlier, there is a possibility you may make a mistake (especially if the code is complicated), and accidentally change its value (& not notice it) before using it. Not that I've ever done that, of course....