[重构]1.关于提炼方法,变量,类

1.提炼方法

该提炼方法:

  • 方法太长的时候需要提炼,否则太长的函数难以阅读,每个方法6行以内是最好的
  • 用来代替只用一次的临时变量,如果有一个临时变量只要用一次,它是由一系列步骤生成的,那么可以用方法来代替这个临时变量,比如:
double avgScope= total / number;
if (avgScope < 10) {
	return "Good";
}

变成:

if (avgScope() < 10) {
	return "Good";
}
private avgScope(){
	return total / number;
}

不该提炼方法:

  • 方法内容其实很简单,不提炼比提炼更容易理解,这个时候不需要提炼

2.提炼变量

该提炼:

  • 用boolean类型临时变量来代替一个复杂的条件,这个时候变量会更简洁
// BAD CODE
if((quantity > 50) || ((quantity * price) > 500)) {
  quantityDiscount = .10;
} else if((quantity > 25) || ((quantity * price) > 100)) {
  quantityDiscount = .07;
 } else if((quantity >= 10) || ((quantity * price) > 50)) {
uantityDiscount = .05;
}
// GOOD CODE
final boolean over50Products = (quantity > 50) || ((quantity * price) > 500);

final boolean over25Products = (quantity > 25) || ((quantity * price) > 100);

final boolean over10Products = (quantity >= 10) || ((quantity * price) > 50);

if(over50Products) {
  quantityDiscount = .10;
} else if(over25Products) {
  quantityDiscount = .07;
} else if(over10Products) {
  quantityDiscount = .05;
}
  • 有很多一个复杂的四则运算,应该用临时变量来代替某些复杂计算的整体
// BAD CODE
System.out.println("Total cost for " + product.getQuantity() + " " + product.getName() + "s is $" + product.getTotalCost());
System.out.println("Cost per product " + product.getTotalCost() / product.getQuantity());
System.out.println("Savings per product " + ((product.getPrice() + product.getShippingCost()) - (product.getTotalCost() / product.getQuantity())) + "\n");
// GOOD CODE
final int numOfProducts = product.getQuantity(); 
final String prodName = product.getName();
final double cost = product.getTotalCost();
final double costWithDiscount = product.getTotalCost() / product.getQuantity();
final double costWithoutDiscount = product.getPrice() + product.getShippingCost();
System.out.println("Total cost for " + numOfProducts + " " + prodName + "s is $" + cost);
System.out.println("Cost per product " + costWithDiscount);
System.out.println("Savings per product " + (costWithoutDiscount - costWithDiscount));
System.out.println()

注意:不应该用同一个临时变量来表示多个不同的运算状态

// BAD CODE
double price = totalCost / numberOfProducts;
price = price + shipping;
price = temp - discount;
// GOOD CODE
double individualPrice = totalCost / numberOfProducts;
double individualPriceWithShipping = individualPrice + shipping;
double price = individualPriceWithShipping - discount;

3.将字段提炼类

该提炼:

  • 某些字段组成一个完整的概念时,应该提炼,比如国家,省,市,区,街道这几个字段如果放在同一个User类里面,可以提炼一个Address类

参考文献:
http://www.newthinktank.com/category/web-design/object-oriented-programming/page/2/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值