傻瓜都能写出计算机可以理解的代码。唯有写出人类容易理解的代码的才是优秀的程序员。 — 《重构,改善既有代码的设计》
重构的原始案例
案例:一个喜剧演出团的账单函数,根据观众人数及剧目类型来向客户收费,并打印出详单。
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);}break;default:throw new Error(`unkonw type: ${play.type}`);}volumeCredits += Math.max(perf.audience - 30, 0);if (play.type === 'comedy') volumeCredits += Math.floor(perf.audience / 5);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;}
重构步骤
重构前,先检查自己是否有一套可靠的测试集。这些测试必须有自我检验能力。
重构前必须先了解这些代码在做什么?
1. 分解函数
提炼计算逻辑
function amountFor() {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);}break;default:throw new Error(`unkonw type: ${play.type}`);}return thisAmount;}function playFor(performance) {return plays[performance.playID]}function volumeCreditsFor(perf) {let volumeCredits = 0;volumeCredits += Math.max(perf.audience - 30, 0);if (play.type === 'comedy') volumeCredits += Math.floor(perf.audience / 5);return volumeCredits;}function format(number) {return new Intl.NumberFormat('en-US', {style: 'currency',currency: 'USD',minimumFractionDigits: 2}).format(number);}
同时拆分循环之后的statement函数
function statement(invoice, plays) {let totalAmount = 0;let volumeCredits = 0;let result = `Statement for ${invoice.customer}\n`;for (let perf of invoice.performances) {result += ` ${play.name}: ${format(amountFor(perf) / 100)} (${perf.audience} seats)}\n`;}for (let perf of invoice.performances) {totalAmount += amountFor(perf);}for (let perf of invoice.performances) {volumeCredits += volumeCreditsFor(perf);}result += `Amount owed is ${format(totalAmount / 100)}\n`;result += `You earned ${volumeCredits} credits\n`;return result;}
再提炼出计算逻辑并将format函数更名为usd
function statement() {let totalAmount = 0;let result = `Statement for ${invoice.customer}\n`;for (let perf of invoice.performances) {result += ` ${play.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 totalAmount = 0;for (let perf of invoice.performances) {totalAmount += amountFor(perf);}return totalAmount;}function totalVolumeCredits() {let volumeCredits = 0;for (let perf of invoice.performances) {volumeCredits += volumeCreditsFor(perf);}return volumeCredits;}function usd(number) {return new Intl.NumberFormat('en-US', {style: 'currency',currency: 'USD',minimumFractionDigits: 2}).format(number / 100);}function amountFor() {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);}break;default:throw new Error(`unkonw type: ${play.type}`);}return thisAmount;}function playFor(performance) {return plays[performance.playID]}function volumeCreditsFor(perf) {let volumeCredits = 0;volumeCredits += Math.max(perf.audience - 30, 0);if (play.type === 'comedy') volumeCredits += Math.floor(perf.audience / 5);return volumeCredits;}}
2. 拆分计算与格式化
将逻辑分为两部分:一部分计算详单所需的数据,另一部分将数据渲染成文本或HTML。
funtion statement(invoice, plays) {return renderPlainText(invoice, plays);}function renderPlainText(invoice, plays) {let totalAmount = 0;let result = `Statement for ${invoice.customer}\n`;for (let perf of invoice.performances) {result += ` ${play.name}: ${usd(amountFor(perf))} (${perf.audience} seats)}\n`;}result += `Amount owed is ${usd(totalAmount())}\n`;result += `You earned ${totalVolumeCredits()} credits\n`;return result;}
创建一个statementData对象,作为在两个阶段传递的中转数据结构。
funtion statement(invoice, plays) {
const statementData = {};
statementData.customer = invoice.customer;
statementData.performances = invoice.performances.map(enrichPerformance);
statementData.totalAmount = totalAmount(result);
statementData.totalVolumeCredits = totalVolumeCredits(result);
return renderPlainText(statementData, plays);
function enrichPerformance(performance) {
const result = Object.assign({}, performance);
result.play = playFor(performance);
result.amount = amountFor(result);
result.volumeCredits = volumeCreditsFor(result)
return result;
}
function renderPlainText(data, plays) {
let totalAmount = 0;
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 ${data.totalAmount}\n`;
result += `You earned ${data.totalVolumeCredits} credits\n`;
return result;
}
}
将statementData交给createStatementData函数生成,同时加入渲染函数后,分为两个文件。
// statement.js
function statement(invoice, plays) {
return renderPlainText(createStatementData(invoice, plays))
}
function htmlStatement() {
return renderHtml(createStatementData(invoice, plays))
}
// createStatementData.js
function createStatementData(invoice, plays) {}
3. 按类重组计算过程
接下来,想要为程序添加下一个特性:支持更多类型的戏剧,以及支持它们各自的价格计算和积分计算。
要为程序引入结构、显式的表达出“计算逻辑的差异是由类型代码确定”有许多途径,不过最自然的解决办法还是使用面向对象世界里的—-类型多态。
在createStatementData中,enrichPerformance函数用来计算每场演出的数据,所以在enrichPerformance函数中引入演出计算器类(PerformanceCalculator)。
class PerformanceCalculator {
constructor(performance, play) {
this.performance = performance;
this.play = play;
}
}
class TragedyCalculator extends PerformanceCalculator {}
class ComedyCalculator extends PerformanceCalculator {}
在enrichPerformance函数中,添加计算器实例,实例用工厂函数生成。
function enrichPerformance(performance) {
const calculator = createPerformanceCaculator(
performance,
playFor(performance)
);
const result = Object.assign({}, performance);
result.play = calculator.play;
result.amount = calculator.amount;
result.volumeCredits = calculator.volumeCredits;
return result;
}
function createPerformanceCaculator(performance, play) {
switch (play.type) {
case 'tragedy':
return new TragedyCalculator(performance, play);
case 'comedy':
return new ComedyCalculator(performance, play);
default:
throw new Error(`Unkonwn type ${play.type}`);
}
}
重构后的代码
statement.ts
import {
iInvoice,
iStatementData,
createStatementData
} from './createStatementData';
export function statement(invoice: iInvoice, plays: object): string {
return renderPlainText(createStatementData(invoice, plays));
}
export function htmlState(invoice: iInvoice, plays: object): string {
return renderHtml(createStatementData(invoice, plays));
}
function renderPlainText(data: iStatementData): string {
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 renderHtml(data: iStatementData): string {
let result = `<h1>Statement for ${data.customer}</h1>`;
result += `<table>\n`;
result += `<tr><th>play</th><th>seats</th><th>cost</th>`;
for (let perf of data.performances) {
result += `<tr><td>${perf.play.name}</td>${perf.audience}<td></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}</em> credits</p>\n`;
return result;
}
function usd(number: number): string {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
}).format(number / 100);
}
createStatementData.ts
export interface iPeformance {
playID: string;
play?: iPlay;
amount?: number;
volumeCredits?: number;
audience: number;
}
export interface iInvoice {
customer: string;
performances: iPeformance[];
}
export interface iPlay {
name: string;
type: string;
}
export interface iStatementData {
customer: string;
performances: iPeformance[];
totalAmount: number;
totalVolumeCredits: number;
}
export function createStatementData(
invoice: iInvoice,
plays: object
): iStatementData {
const result: iStatementData = Object.create({});
result.customer = invoice.customer;
result.performances = invoice.performances.map(enrichPerformance);
result.totalAmount = totalAmount(result);
result.totalVolumeCredits = totalVolumeCredits(result);
return result;
function enrichPerformance(performance: iPeformance): iPeformance {
const calculator = createPerformanceCaculator(
performance,
playFor(performance)
);
const result = Object.assign({}, performance);
result.play = calculator.play;
result.amount = calculator.amount;
result.volumeCredits = calculator.volumeCredits;
return result;
}
function createPerformanceCaculator(performance: iPeformance, play: iPlay) {
switch (play.type) {
case 'tragedy':
return new TragedyCalculator(performance, play);
case 'comedy':
return new ComedyCalculator(performance, play);
default:
throw new Error(`Unkonwn type ${play.type}`);
}
}
function playFor(performance: iPeformance): iPlay {
return plays[performance.playID];
}
function totalVolumeCredits(data: any): number {
return data.performances.reduce(
(total: number, p: any) => total + p.volumeCredits,
0
);
}
function totalAmount(data: any): number {
return data.performances.reduce(
(total: number, p: any) => total + p.amount,
0
);
}
}
class PerformanceCalculator {
performance: iPeformance;
play: iPlay;
constructor(performance: iPeformance, play: iPlay) {
this.performance = performance;
this.play = play;
}
get volumeCredits(): number {
return Math.max(this.performance.audience - 30, 0);
}
}
class TragedyCalculator extends PerformanceCalculator {
constructor(performance: iPeformance, play: iPlay) {
super(performance, play);
}
get amount(): number {
let result: number = 40000;
if (this.performance.audience > 30) {
result += 1000 * (this.performance.audience - 30);
}
return result;
}
}
class ComedyCalculator extends PerformanceCalculator {
constructor(performance: iPeformance, play: iPlay) {
super(performance, play);
}
get amount(): number {
let result = 30000;
if (this.performance.audience > 20) {
result += 10000 + 500 * (this.performance.audience - 20);
}
return result;
}
get volumeCredits(): number {
return super.volumeCredits + Math.floor(this.performance.audience / 5);
}
}
