Replace Static Variable with Parameter (by Marian Vittek) <IMG SRC = "http://www.refactoring.com/catalog/new.gif" border=0>
2003. 8. 3. 12:10
Replace Static Variable with Parameter
Refactoring contributed by Marian Vittek
A function depending on a static variable needs to be reused in more general context.
Add a new parameter to the function and replace all references of the static variable within the function by this new parameter.
void printValues() {
for (int i = 0; i < people.length; i++) {
System.out.println(people[i].name+" has salary "+people[i].salary);
}
}
public static void main(String args[]) {
...
printValues();
}
![](http://www.refactoring.com/catalog/arrow.gif)
void printValues(PrintStream outfile) {
for (int i = 0; i < people.length; i++) {
outfile.println(people[i].name+" has salary "+people[i].salary);
}
}
public static void main(String args[]) {
...
printValues(System.out);
}
Motivation
The original function is using a static variable, but you wish either to reuse the function in new project (not containing the static variable) or reuse the function in the same project but in more general context.Mechanics
- If the function calls other functions using the static variable in question, then use this refactoring on all those invoked functions first.
- Use Add Parameter to add a new argument to the function
- Add the static variable as actual argument to all callers of this function in.
- Replace all references to the static variable within the function by the new argument
***** 아름다운프로님에 의해서 게시물 복사 + 카테고리변경되었습니다 (2003-12-18 17:27)