重构,第一个示例
为何,以及如何提炼一个函数
如何处理过长的函数
A First Set of Refactorings
Split Phase
Encapsulate Variable
let defaultOwner = { firstName: "Martin", lastName: "Fowler" };
// after encapsulate variable
let defaultOwnerData = { firstName: "Martin", lastName: "Fowler" };
export function defaultOwner() { return defaultOwnerData; }
export function setDefaultOwner(arg) { defaultOwnerData = arg; }
Combine Funtion into Class
使用类,将数据与函数捆绑,为数据与函数提供一个共同环境
Combine Functino into Transform
类似结构型设计模式中的monkey patching 猴子补丁
const rawReading = acquireReading();
const aReading = enrichReading(rawReading);
const basicChargeAmount = aReading.baseCharge; // 将逻辑封装到 enrichReading
function enrichReading(original) {
const result = _.cloneDeep(original);
result.baseCharge = calculateBaseCharge(result);
return result;
}
Introduce Parameter Object
将共有行为的数据
放入一个类中,如找出温度在(50~55)之外的元素
Encapsulation
Encapsulate Collection
Encapsulate Record
organization = { name: "Acme Gooseberries", country: "GB" };
// after encapsulate record
class Organization {
constructor(data) {
this._name = data.name;
this._country = data.country;
}
get name() { return this._name; }
set name(arg) { this._name = arg; }
get country() { return this._country; }
set country(arg) { this._country = arg; }
}
Replace Primitive with Object
orders.filter(o => "high" === o.priority
|| "rush" === o.priority);
// after replace primitive with object
orders.filter(o => o.priority.higherThan(new Priority("normal")))
Replace Temp with Query
临时变量 -> Query (Class -> get value())
Organizing Data
Split Variable
一个变量,多种用途,将其拆成两个变量
let tmp = 2 * (height + width)
console.log(tmp)
tmp = height * width
console.log(tmp)
after split variable
const perimeter = 2 * (height + width)
console.log(perimeter)
const area = height * width
console.log(area)
Replace Derived Variable with Query
将可变数据的作用域限制到最小
如下例子:添加数据的时候还要计算 total
,将计算total
的逻辑单独移出来
Refactoring API
Separate Query from Modifier
将查询函数
与副作用函数
分离
Replace Parameter with Query
Perserve Whole Object
传递整个对象能够更好地应对变化
,同时还能缩短参数列表
Replace Function with Command
在类中,将参数的传递放入构造器中
而非某个方法中
,可以非常直观的得出该类需要那些参数