重构第一个示例
《重构 改善既有代码的设计》 马丁 富勒
第一章
戏剧演出团原始代码
invoices.json
[ { "customer": "BigCo", "performances": [ { "playId": "hamlet", "audience": 55 }, { "playId": "as-like", "audience": 35 }, { "playId": "othello", "audience": 40 } ] } ]
plays.json
{ "hamlet": {"name": "Hamlet", "type": "tragedy"}, "as-like": {"name": "As You Like It", "type": "comedy"}, "othello": {"name": "Othello", "type": "tragedy"} }
main.js
const invoices = require('./invoices.json') const plays = require('./plays.json') function statement (invoice, plays) { let totalAmount = 0; let volumeCredits = 0; let result = `Statement for ${invoice.customer}\n`; const format = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2 }).format; for (let perf of invoice.performances) { const play = plays[perf.playId]; let thisAmount = 0; switch (play.type) { case "tragedy": thisAmount = 40000; if(perf.audience > 30) { thisAmount += 1000 * (perf.audience - 30); } break; case "comedy": thisAmount = 30000; if (perf.audience > 20) { thisAmount += 10000 + 500 * (perf.audience - 20); } thisAmount += 300 * perf.audience; break; default: throw new Error(`unknow type: ${play.type}`); } // add volume credits volumeCredits += Math.max(perf.audience - 30, 0); // add extra credit for every ten comedy attendees if("comedy" === play.type) volumeCredits += Math.floor(perf.audience / 5); // print line for this order result += ` ${play.name}: ${format(thisAmount/100)} (${perf.audience} seats)\n`; totalAmount += thisAmount } result += `Amount owed is ${format(totalAmount/100)}\n`; result += `You earned ${volumeCredits} credits\n`; return result; } console.log(statement(invoices[0], plays));
运行结果
------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- -------------------------
将原函数分解成一组嵌套函数。 增加可读性。 (提炼函数)
// 为了可视化 import invoice from './invoices.js'; import plays from './plays.js'; function statement (invoice, plays) { let result = `Statement for ${invoice.customer}\n`; for (let perf of invoice.performances) { result += ` ${playFor(perf).name}: ${usd(amountFor(perf))} (${perf.audience} seats)\n`; } result += `Amount owed is ${usd(totalAmount())}\n`; result += `You earned ${totalVolumeCredits()} credits\n`; return result; } function totalAmount() { let result = 0; for (let perf of invoice.performances) { result += amountFor(perf); } return result; } function totalVolumeCredits() { let result = 0; for (let perf of invoice.performances) { result += volumeCreditsFor(perf); } return result; } function usd(aNumber) { return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2 }).format(aNumber/100) } function volumeCreditsFor(perf) { let result = 0; result += Math.max(perf.audience - 30, 0); if("comedy" === playFor(perf).type) result += Math.floor(perf.audience / 5); return result; } function playFor(aPerformance) { return plays[aPerformance.playId]; } function amountFor(aPerformance) { let result = 0; switch (playFor(aPerformance).type) { case "tragedy": result = 40000; if(aPerformance.audience > 30) { result += 1000 * (aPerformance.audience - 30); } break; case "comedy": result = 30000; if (aPerformance.audience > 20) { result += 10000 + 500 * (aPerformance.audience - 20); } result += 300 * aPerformance.audience; break; default: throw new Error(`unknow type: ${playFor(aPerformance).type}`); } return result; } console.log(statement(invoice, plays));
分离计算逻辑和输入格式化逻辑。 为了拓展HTML合适。 通过 内联变量和搬移函数
// 提高复用性 可以分外 statement.js 和 createStatementData.js // const invoice = require('./invoices.json')[0] // const plays = require('./plays.json') import invoice from './invoices.js'; import plays from './plays.js'; function statement (invoice, plays) { return renderPlainText(createStatementData (invoice, plays)); function createStatementData (invoice, plays) { const statementData = {}; statementData.customer = invoice.customer; statementData.performances = invoice.performances.map(enrichPerformance); statementData.totalAmount = totalAmount(statementData); statementData.totalVolumeCredits = totalVolumeCredits(statementData); return statementData; } function totalAmount(data) { return data.performances .reduce((total, perf) => total + perf.amount, 0); } function totalVolumeCredits(data) { return data.performances .reduce((total, perf) => total + perf.volumeCredits, 0); } function enrichPerformance(aPerformance) { const result = Object.assign({}, aPerformance); result.play = playFor(result) result.amount = amountFor(result) result.volumeCredits = volumeCreditsFor(result) return result; } function playFor(aPerformance) { return plays[aPerformance.playId]; } function amountFor(aPerformance) { let result = 0; switch (aPerformance.play.type) { case "tragedy": result = 40000; if(aPerformance.audience > 30) { result += 1000 * (aPerformance.audience - 30); } break; case "comedy": result = 30000; if (aPerformance.audience > 20) { result += 10000 + 500 * (aPerformance.audience - 20); } result += 300 * aPerformance.audience; break; default: throw new Error(`unknow type: ${aPerformance.play.type}`); } return result; } function volumeCreditsFor(aPerformance) { let result = 0; result += Math.max(aPerformance.audience - 30, 0); if("comedy" === aPerformance.play.type) result += Math.floor(aPerformance.audience / 5); return result; } } function renderPlainText (data) { let result = `Statement for ${data.customer}\n`; for (let perf of data.performances) { result += ` ${perf.play.name}: ${usd(perf.amount)} (${perf.audience} seats)\n`; } result += `Amount owed is ${usd(data.totalAmount)}\n`; result += `You earned ${data.totalVolumeCredits} credits\n`; return result; function usd(aNumber) { return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2 }).format(aNumber/100) } } console.log(statement(invoice, plays));
以多态取代条件表达式,为了拓展有多个类型戏剧演出。
createStatementData .js
import { PerformanceCalculator, TragedyCalculator, ComedyCalculator } from './PerformanceCalculator.js'; export default function createStatementData (invoice, plays) { const result = {}; result.customer = invoice.customer; result.performances = invoice.performances.map(enrichPerformance); result.totalAmount = totalAmount(result); result.totalVolumeCredits = totalVolumeCredits(result); return result; function totalAmount(data) { return data.performances .reduce((total, perf) => total + perf.amount, 0); } function totalVolumeCredits(data) { return data.performances .reduce((total, perf) => total + perf.volumeCredits, 0); } function createPerformanceCalculator(aPerformance, aPlay) { switch(aPlay.type) { case "tragedy" : return new TragedyCalculator(aPerformance, aPlay); case "comedy" : return new ComedyCalculator(aPerformance, aPlay); default: throw new Error(`unknow type: ${aPlay.type}`); } return new PerformanceCalculator(aPerformance, aPlay); } function enrichPerformance(aPerformance) { const calculator = createPerformanceCalculator(aPerformance, playFor(aPerformance)) const result = Object.assign({}, aPerformance); result.play = calculator.play; result.amount = calculator.amount; result.volumeCredits = calculator.volumeCredits; return result; } function playFor(aPerformance) { return plays[aPerformance.playId]; } /* function amountFor(aPerformance) { let result = 0; switch (aPerformance.play.type) { case "tragedy": result = 40000; if(aPerformance.audience > 30) { result += 1000 * (aPerformance.audience - 30); } break; case "comedy": result = 30000; if (aPerformance.audience > 20) { result += 10000 + 500 * (aPerformance.audience - 20); } result += 300 * aPerformance.audience; break; default: throw new Error(`unknow type: ${aPerformance.play.type}`); } return result; } function volumeCreditsFor(aPerformance) { let result = 0; result += Math.max(aPerformance.audience - 30, 0); if("comedy" === aPerformance.play.type) result += Math.floor(aPerformance.audience / 5); return result; } */ };
statement.js
import createStatementData from './createStatementData.js'; import invoice from './invoices.js'; import plays from './plays.js'; function statement (invoice, plays) { return renderPlainText(createStatementData (invoice, plays)); } function renderPlainText (data) { let result = `Statement for ${data.customer}\n`; for (let perf of data.performances) { result += ` ${perf.play.name}: ${usd(perf.amount)} (${perf.audience} seats)\n`; } result += `Amount owed is ${usd(data.totalAmount)}\n`; result += `You earned ${data.totalVolumeCredits} credits\n`; return result; } function htmlStatement(invoice, plays) { return renderHtml(createStatementData(invoice, plays)); } function renderHtml(data) { let result = `<h1>Statement for ${data.customer}</h1>\n`; result += "<table>\n" result += "<tr><th>play</th><th>seats</th><th>cost</th></tr>\n" for (let perf of data.performances) { result += ` <tr><td>${perf.play.name}</td><td>${perf.audience}</td>`; result += `<td>${usd(perf.amount)}</td><tr>\n`; } result += "</table>\n" result += `<p>Amount owed is <em>${usd(data.totalAmount)}</em></p>\n`; result += `<p>You earned <em>${data.totalVolumeCredits} credits</em></p>\n`; return result; } function usd(aNumber) { return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2 }).format(aNumber/100) } export default function() { console.log(htmlStatement(invoice, plays)); }
PerformanceCalculator.js
class PerformanceCalculator { constructor(aPerformance, aPlay) { this.performance = aPerformance; this.play = aPlay; } get amount() { throw new Error(`subclass responnsibility`); } get volumeCredits() { return Math.max(this.performance.audience - 30, 0);; } } class TragedyCalculator extends PerformanceCalculator { get amount() { let result = 40000; if(this.performance.audience > 30) { result += 1000 * (this.performance.audience - 30); } return result; } } class ComedyCalculator extends PerformanceCalculator { get amount() { let result = 30000; if (this.performance.audience > 20) { result += 10000 + 500 * (this.performance.audience - 20); } result += 300 * this.performance.audience; return result; } get volumeCredits() { return super.volumeCredits + Math.floor(this.performance.audience / 5); } } export { PerformanceCalculator, TragedyCalculator, ComedyCalculator };
在重构过程中最重要的一点,每个小步进行测试。 遇到问题便可以及时处理。
1. 重构时先要读懂代码, 然后让代码可视化更强。最常用的手段就是提取函数。
2. 为了拓展功能,修改原来的设计手段。 例如拆分逻辑 或增加多态。
好代码的检验标准就是人们是否能轻而易举的修改它。