You have code that first declares a variable and then assigns a value to it
Make it into a direct initialization instead
void foo() { int i; // .... i = 7; }
void foo() { // ... int i = 7; }
You often see functions in which the programmer has first declared lots of variables that will be used in that function, and then, further down the function, assigns values to them. This is often an artifact from older programming languages, where you had to declare in the beginning of the function all variables that are used in it. In C++ and Java this is not necessary, and in C++ this old style of programming can give you slower programs, since a declaration of a variable in C++ often means a call to the default constructor. In Java, declarations of variables are cheap, if not even free, but the problem is that you end up with unnecessary lines of code that adds no value to your program - you have two lines of code that can be expressed with one line of code. Another problem is the risk that at some parts of the program a variable is not explicitly initialized, so that its initial value may not be obvious, or even undefined, as is often the case in C++.
Start with this code.
void foo() { int i; // .... i = 7; }
The first move is to move the declaration of the variable to just before where it is assigned to:
void foo() { // .... int i; i = 7; }
I can now compile and test this. The most common mistake is that you have reduced the scope of the variable so that it no longer is in scope at some other place where it is used. Fortunately C++ and Java compilers will give you and error if this has happened.
Then it is time to replace the declaration + assignment with the initialization:
void foo() { // .... int i = 7; }
If this also compiles and runs as before, then it is the end of the refactoring.
However if the value of i
doesn't change, then it's a good idea to make that explicit by declaring i
as final
void foo() { // .... final int i = 7; }