提炼函数
1 | function printOwing(invoice) { |
重构前函数
1 | function printOwing(invoice) { |
范例:有局部变量
1 | function printOwing(invoice) { |
范例:对局部变量再赋值
1 | function printOwing(invoice) { |
内联函数
1 | function getRating(driver) { |
提炼变量
1 | return ( |
重构前函数
1 | class Order { |
范例:在一个类中
1 | class Order { |
内联变量
1 | let basePrice = anOrder.basePrice; |
改变函数声明
1 | function circum(radius) {...} |
重构前函数
1 | function inNewEngland(aCustomer) { |
范例:把参数改为属性
1 | function inNewEngland(stateCode) { |
封装变量
1 | let defaultOwner = { firstName: 'Martin', lastName: 'Fowler' }; |
控制引用变量修改
1 | let defaultOwner = { firstName: 'Martin', lastName: 'Fowler' }; |
函数改名
1 | let a = height * width; |
引入参数对象
1 | function amountInvoiced(startDate, endDate) {...} |
重构前函数
1 | const station = { |
第一步:将最大值、最小值生命为一个类
1 | class NumberRange { |
第二步:修改判断逻辑
1 | const range = new NumberRange( |
第三步:将判断逻辑封装函数
1 | function readingsOutsideRange(station, range) { |
函数组合成类
1 | function base(aReading) {...} |
重构前函数
1 | reading = { customer: 'ivan', quantity: 10, month: 5, year: 2017 }; |
第一步:封装类
1 | class Reading { |
第二步:搬移已有函数
1 | class Reading { |
函数组合成变换
1 | function base(aReading) {...} |
重构前函数同函数组合成类
一致
重构后
1 | function enrichReading(original) { |
缺点
如果在代码地方修改了原始数据(reading),会出现数据不一致的情况。避免这种情况的方式是使用函数组合成类
这种手法
拆分阶段
1 | const orderData = orderString.split(/\s+/); |
重构前函数
1 | function priceOrder(product, quantity, shippingMethod) { |
第一步:提炼函数
1 | function priceOrder(product, quantity, shippingMethod) { |
第二步:中转数据(引入参数对象)
1 | function priceOrder(product, quantity, shippingMethod) { |
版权声明
以上代码来自重构 第2版:改善既有代码的设计
,在此感谢