系列文章目录
重构(第二版) 读书笔记 第一章(从一个小程序入手,开始我们的第一次重构)
前言
上一篇文章我们对一段程序进行了基础的重构,并完成了以html格式打印详单的需求。这次我们来完成第二个需求:演员尝试更多的戏剧类型,对于新增的戏剧类型有新的计分方式。
上一篇代码最后的状态如下:
createStatementData.js
export default 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 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(`unknown type: ${
data.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 totalAmount(data) {
return data.performances
.reduce((total, p) => total + p.amount, 0);
}
function totalVolumeCredits(data) {
return data.performances
.reduce((total, p) => total + p.volumeCredits, 0);
}
}
statement.js
import createStatementData from "./createStatementData.js";
const playsData = {
"hamlet": {
"name": "Hamlet", "type": "tragedy" },
"as-like": {
"name": "As You Like It", "type": "comedy" },
"othello": {
"name": "Othello", "type": "tragedy" }
}
const invoicesData = {
"customer": "BigCo