Replace Assignment with Initialization (by Mats Henricson) <IMG SRC = "http://www.refactoring.com/catalog/new.gif" border=0>
2003. 8. 2. 14:55
Replace Assignment with Initialization
Refactoring contributed by Mats Henricson
Make it into a direct initialization instead
void foo() {
int i;
// ....
i = 7;
}
![](http://www.refactoring.com/catalog/arrow.gif)
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
- Move the declaration of the variable to where that variable is first used,
just before the assignment, making sure that you haven't reduced the scope
of the variable so that it isn't in scope at some other place where it
is used - Compile and test
- Replace the declaration and assignment with a direct initialization
- Compile and test
- If appropriate, declare the temp as final, and compile and test again.
Example
- 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 finalvoid foo() {
// ....
final int i = 7;
}
***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 17:27)