傻瓜都能写出计算机可以理解的代码。唯有写出人类容易理解的代码的才是优秀的程序员。 — 《重构,改善既有代码的设计》

重构的原始案例

案例:一个喜剧演出团的账单函数,根据观众人数及剧目类型来向客户收费,并打印出详单。

  1. function statement(invoice, plays) {
  2. let totalAmount = 0;
  3. let volumeCredits = 0;
  4. let result = `Statement for ${invoice.customer}\n`;
  5. const format = new Intl.NumberFormat('en-US', {
  6. style: 'currency',
  7. currency: 'USD',
  8. minimumFractionDigits: 2
  9. }).format;
  10. for (let perf of invoice.performances) {
  11. const play = plays[perf.playID];
  12. let thisAmount = 0;
  13. switch (play.type) {
  14. case 'tragedy':
  15. thisAmount = 40000;
  16. if (perf.audience > 30) {
  17. thisAmount += 1000 * (perf.audience - 30);
  18. }
  19. break;
  20. case 'comedy':
  21. thisAmount = 30000;
  22. if (perf.audience > 20) {
  23. thisAmount += 10000 + 500 * (perf.audience - 20);
  24. }
  25. break;
  26. default:
  27. throw new Error(`unkonw type: ${play.type}`);
  28. }
  29. volumeCredits += Math.max(perf.audience - 30, 0);
  30. if (play.type === 'comedy') volumeCredits += Math.floor(perf.audience / 5);
  31. result += ` ${play.name}: ${format(thisAmount / 100)} (${
  32. perf.audience
  33. } seats)}\n`;
  34. totalAmount += thisAmount;
  35. }
  36. result += `Amount owed is ${format(totalAmount / 100)}\n`;
  37. result += `You earned ${volumeCredits} credits\n`;
  38. return result;
  39. }

重构步骤

重构前,先检查自己是否有一套可靠的测试集。这些测试必须有自我检验能力。

重构前必须先了解这些代码在做什么?

1. 分解函数

提炼计算逻辑

  1. function amountFor() {
  2. let thisAmount = 0;
  3. switch (play.type) {
  4. case 'tragedy':
  5. thisAmount = 40000;
  6. if (perf.audience > 30) {
  7. thisAmount += 1000 * (perf.audience - 30);
  8. }
  9. break;
  10. case 'comedy':
  11. thisAmount = 30000;
  12. if (perf.audience > 20) {
  13. thisAmount += 10000 + 500 * (perf.audience - 20);
  14. }
  15. break;
  16. default:
  17. throw new Error(`unkonw type: ${play.type}`);
  18. }
  19. return thisAmount;
  20. }
  21. function playFor(performance) {
  22. return plays[performance.playID]
  23. }
  24. function volumeCreditsFor(perf) {
  25. let volumeCredits = 0;
  26. volumeCredits += Math.max(perf.audience - 30, 0);
  27. if (play.type === 'comedy') volumeCredits += Math.floor(perf.audience / 5);
  28. return volumeCredits;
  29. }
  30. function format(number) {
  31. return new Intl.NumberFormat('en-US', {
  32. style: 'currency',
  33. currency: 'USD',
  34. minimumFractionDigits: 2
  35. }).format(number);
  36. }

同时拆分循环之后的statement函数

  1. function statement(invoice, plays) {
  2. let totalAmount = 0;
  3. let volumeCredits = 0;
  4. let result = `Statement for ${invoice.customer}\n`;
  5. for (let perf of invoice.performances) {
  6. result += ` ${play.name}: ${format(amountFor(perf) / 100)} (${
  7. perf.audience
  8. } seats)}\n`;
  9. }
  10. for (let perf of invoice.performances) {
  11. totalAmount += amountFor(perf);
  12. }
  13. for (let perf of invoice.performances) {
  14. volumeCredits += volumeCreditsFor(perf);
  15. }
  16. result += `Amount owed is ${format(totalAmount / 100)}\n`;
  17. result += `You earned ${volumeCredits} credits\n`;
  18. return result;
  19. }

再提炼出计算逻辑并将format函数更名为usd

  1. function statement() {
  2. let totalAmount = 0;
  3. let result = `Statement for ${invoice.customer}\n`;
  4. for (let perf of invoice.performances) {
  5. result += ` ${play.name}: ${usd(amountFor(perf))} (${
  6. perf.audience
  7. } seats)}\n`;
  8. }
  9. result += `Amount owed is ${usd(totalAmount())}\n`;
  10. result += `You earned ${totalVolumeCredits()} credits\n`;
  11. return result;
  12. function totalAmount() {
  13. let totalAmount = 0;
  14. for (let perf of invoice.performances) {
  15. totalAmount += amountFor(perf);
  16. }
  17. return totalAmount;
  18. }
  19. function totalVolumeCredits() {
  20. let volumeCredits = 0;
  21. for (let perf of invoice.performances) {
  22. volumeCredits += volumeCreditsFor(perf);
  23. }
  24. return volumeCredits;
  25. }
  26. function usd(number) {
  27. return new Intl.NumberFormat('en-US', {
  28. style: 'currency',
  29. currency: 'USD',
  30. minimumFractionDigits: 2
  31. }).format(number / 100);
  32. }
  33. function amountFor() {
  34. let thisAmount = 0;
  35. switch (play.type) {
  36. case 'tragedy':
  37. thisAmount = 40000;
  38. if (perf.audience > 30) {
  39. thisAmount += 1000 * (perf.audience - 30);
  40. }
  41. break;
  42. case 'comedy':
  43. thisAmount = 30000;
  44. if (perf.audience > 20) {
  45. thisAmount += 10000 + 500 * (perf.audience - 20);
  46. }
  47. break;
  48. default:
  49. throw new Error(`unkonw type: ${play.type}`);
  50. }
  51. return thisAmount;
  52. }
  53. function playFor(performance) {
  54. return plays[performance.playID]
  55. }
  56. function volumeCreditsFor(perf) {
  57. let volumeCredits = 0;
  58. volumeCredits += Math.max(perf.audience - 30, 0);
  59. if (play.type === 'comedy') volumeCredits += Math.floor(perf.audience / 5);
  60. return volumeCredits;
  61. }
  62. }

2. 拆分计算与格式化

将逻辑分为两部分:一部分计算详单所需的数据,另一部分将数据渲染成文本或HTML。

  1. funtion statement(invoice, plays) {
  2. return renderPlainText(invoice, plays);
  3. }
  4. function renderPlainText(invoice, plays) {
  5. let totalAmount = 0;
  6. let result = `Statement for ${invoice.customer}\n`;
  7. for (let perf of invoice.performances) {
  8. result += ` ${play.name}: ${usd(amountFor(perf))} (${
  9. perf.audience
  10. } seats)}\n`;
  11. }
  12. result += `Amount owed is ${usd(totalAmount())}\n`;
  13. result += `You earned ${totalVolumeCredits()} credits\n`;
  14. return result;
  15. }

创建一个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);
  }
}