Replace Static Variable with Parameter -- 以参数变量取代静态变量

来源:互联网 发布:尤克里里怎么调音软件 编辑:程序博客网 时间:2024/05/19 02:42

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

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 addParameter to add a new argument to the function
  • 使用AddParameter为函数添加新的参数。
  • 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
  • 以新的参数变量取代所有的静态变量。
原创粉丝点击