重构改善既有代码设计--以函数取代参数

以函数取代参数

对象调用某个函数,并将所得结果作为参数,传递给另一个函数。

动机

如果函数可以通过其他途径(而非参数列)获得参数值,那么它就不应该通过参数获得该值,过长的参数会增加阅读难道。
看看参数接收端是否可以通过与调用端相同的计算来取得参数携带值

  • 通过所属对象内部的另一个函数来计算参数,可以将这个计算过程转移到调用端内,从而去掉参数。
  • 调用的函数隶属另也给对象,让该对象拥有一个reference指向调用端所属对象。
  • 如果参数计算过程依赖调用端某个参数,那么就无法去掉被调用端的那个函数。

作法

  • 如果有必要,将参数的计算过程提炼到一个独立函数中。
  • 函数本体内对该参数的引用替换为对新建函数的调用
  • 每次替换后,修改并测试。
  • 全部替换完成后,使用remove parameter将该参数去掉。

范例

public double getPrice(){
	int basePrice = _quantity * _itemPrice;
	int discountLevel;
	if (_quantity > 100) discountLevel = 2;
	else discountLevel = 1;
	double finalPrice = discountedPrice(basePrice, discountLevel);
	return finalPrice;
}
private double discountedPrice (int basePrice, int discountLevel) {
	if (discountLevel == 2) return basePrice * 0.1;
	else return basePrice * 0.05;
}
=================>
// 抽象计算折扣等级代码
private int getDiscountLevel(){
	if (_quantity > 100) return 2;
	else return 1;
}
public double getPrice(){
	int basePrice = _quantity * _itemPrice;
	int discountLevel = getDiscountLevel();
	return discountedPrice(basePrice, discountLevel);
}
...
=================>
...
// 把discountedPrice() 函数中对discountLevel 参数的所有引用点, 替换为getDiscountLevel() 函数的调用
// Remove Parameter 去掉discountLevel参数
private discountedPrice(int basePrice) {
	if (getDiscountLevel() == 2) return basePrice * 0.1;
	else return basePrice * 0.05;
}
...
private int getBasePrice() {
	return  _quantity * _itemPrice;
}
// 针对discountedPrice使用inline Method
private double getPrice(){
	if (getDiscountLevel() == 2) return getBasePrice() * 0.1;
	else return getBasePrice() * 0.05;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值