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

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
  • 以新的参数变量取代所有的静态变量。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值