Replace Assignment with Initialization

Refactoring contributed by Mats Henricson

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

Motivation

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

Mechanics

Example

| Refactoring Home | | Alphabetical List |