第 12 章 处理继承关系

在最后一章里,我将介绍面向对象编程技术里最为人熟知的一个特性:继承。与任何强有力的特性一样,继承机制十分实用,却也经常被误用,而且常得等你用上一段时间,遇见了痛点,才能察觉误用所在。

特性(主要是函数和字段)经常需要在继承体系里上下调整。我有一组手法专门用来处理此类调整:函数上移(350)、字段上移(353)、构造函数本体上移(355)、函数下移(359)以及字段下移(361)。我可以使用提炼超类(375)、移除子类(369)以及折叠继承体系(380)来为继承体系添加新类或删除旧类。如果一个字段仅仅作为类型码使用,根据其值来触发不同的行为,那么我会通过以子类取代类型码(362),用一个子类来取代这样的字段。

继承本身是一个强有力的工具,但有时它也可能被用于错误的地方,有时本来适合使用继承的场景变得不再合适——若果真如此,我就会用以委托取代子类(381)或以委托取代超类(399)将继承体系转化成委托调用。

12.1 函数上移(Pull Up Method)

反向重构:函数下移(359)

class Employee {...}

class Salesman extends Employee {
 get name() {...}
}

class Engineer extends Employee {
 get name() {...}
}


class Employee {
 get name() {...}
}

class Salesman extends Employee {...}
class Engineer extends Employee {...}

动机

避免重复代码是很重要的。重复的两个函数现在也许能够正常工作,但假以时日却只会成为滋生 bug 的温床。无论何时,只要系统内出现重复,你就会面临“修改其中一个却未能修改另一个”的风险。通常,找出重复也有一定的难度。

如果某个函数在各个子类中的函数体都相同(它们很可能是通过复制粘贴得到的),这就是最显而易见的函数上移适用场合。当然,情况并不总是如此明显。我也可以只管放心地重构,再看看测试程序会不会发牢骚,但这就需要对我的测试有充分的信心。我发现,观察这些可能重复的函数之间的差异往往大有收获:它们经常会向我展示那些我忘记测试的行为。

函数上移常常紧随其他重构而被使用。也许我能找出若干个身处不同子类内的函数,而它们又可以通过某种形式的参数调整成为相同的函数。这时候,最简单的办法就是先分别对这些函数应用函数参数化(310),然后应用函数上移。

函数上移过程中最麻烦的一点就是,被提升的函数可能会引用只出现于子类而不出现于超类的特性。此时,我就得用字段上移(353)和函数上移先将这些特性(类或者函数)提升到超类。

如果两个函数工作流程大体相似,但实现细节略有差异,那么我会考虑先借助塑造模板函数(Form Template Method)[mf-ft]构造出相同的函数,然后再提升它们。

做法

检查待提升函数,确定它们是完全一致的。

如果它们做了相同的事情,但函数体并不完全一致,那就先对它们进行重构,直到其函数体完全一致。

检查函数体内引用的所有函数调用和字段都能从超类中调用到。

如果待提升函数的签名不同,使用改变函数声明(124)将那些签名都修改为你想要在超类中使用的签名。

在超类中新建一个函数,将某一个待提升函数的代码复制到其中。

执行静态检查。

移除一个待提升的子类函数。

测试。

逐一移除待提升的子类函数,直到只剩下超类中的函数为止。

范例

我手上有两个子类,它们之中各有一个函数做了相同的事情:

class Employee extends Party...

get annualCost() {
  return this.monthlyCost * 12;
}

class Department extends Party...

get totalAnnualCost() {
  return this.monthlyCost * 12;
}

检查两个类的函数时我发现,两个函数都引用了 monthlyCost 属性,但后者并未在超类中定义,而是在两个子类中各自定义了一份实现。因为 JavaScript 是动态语言,这样做没有问题;但如果是在一门静态语言里,我就必须将 monthlyCost 声明为 Party 类上的抽象函数,否则编译器就会报错。

两个函数各有不同的名字,因此第一步是用改变函数声明(124)统一它们的函数名。

class Department...

get annualCost() {
  return this.monthlyCost * 12;
}

然后,我从其中一个子类中将 annualCost 函数复制到超类。

class Party...

get annualCost() {
  return this.monthlyCost * 12;
}

在静态语言里,做完这一步我就可以编译一次,确保超类函数的所有引用都能正常工作。但这是在 JavaScript 里,编译显然帮不上什么忙,因此我直接先从 Employee 中移除 annualCost 函数,测试,接着移除 Department 类中的 annualCost 函数。

这项重构手法至此即告完成,但还有一个遗留问题需要解决:annualCost 函数中调用了 monthlyCost,但后者并未在 Party 类中显式声明。当然代码仍能正常工作,这得益于 JavaScript 是动态语言,它能自动帮你调用子类上的同名函数。但若能明确传达出“继承 Party 类的子类需要提供一个 monthlyCost 实现”这个信息,无疑也有很大的价值,特别是对日后需要添加子类的后来者。其中一种好的传达方式是添加一个如下的陷阱(trap)函数。

class Party...

get monthlyCost() {
  throw new SubclassResponsibilityError();
}

我称上述抛出的错误为一个“子类未履行职责错误”,这是从 Smalltalk 借鉴来的名字。

12.2 字段上移(Pull Up Field)

反向重构:字段下移(361)

class Employee {...} // Java

class Salesman extends Employee {
 private String name;
}

class Engineer extends Employee {
 private String name;
}


class Employee {
 protected String name;
}

class Salesman extends Employee {...}
class Engineer extends Employee {...}

动机

如果各子类是分别开发的,或者是在重构过程中组合起来的,你常会发现它们拥有重复特性,特别是字段更容易重复。这样的字段有时拥有近似的名字,但也并非绝对如此。判断若干字段是否重复,唯一的办法就是观察函数如何使用它们。如果它们被使用的方式很相似,我就可以将它们提升到超类中去。

本项重构可从两方面减少重复:首先它去除了重复的数据声明;其次它使我可以将使用该字段的行为从子类移至超类,从而去除重复的行为。

许多动态语言不需要在类定义中定义字段,相反,字段是在第一次被赋值的同时完成声明。在这种情况下,字段上移基本上是应用构造函数本体上移(355)后的必然结果。

做法

针对待提升之字段,检查它们的所有使用点,确认它们以同样的方式被使用。

如果这些字段的名称不同,先使用变量改名(137)为它们取个相同的名字。

在超类中新建一个字段。

新字段需要对所有子类可见(在大多数语言中 protected 权限便已足够)。

移除子类中的字段。

测试。

12.3 构造函数本体上移(Pull Up Constructor Body)

class Party {...}

class Employee extends Party {
 constructor(name, id, monthlyCost) {
  super();
  this._id = id;
  this._name = name;
  this._monthlyCost = monthlyCost;
 }
}


class Party {
 constructor(name){
  this._name = name;
 }
}

class Employee extends Party {
 constructor(name, id, monthlyCost) {
  super(name);
  this._id = id;
  this._monthlyCost = monthlyCost;
 }
}

动机

构造函数是很奇妙的东西。它们不是普通函数,使用它们比使用普通函数受到更多的限制。

如果我看见各个子类中的函数有共同行为,我的第一个念头就是使用提炼函数(106)将它们提炼到一个独立函数中,然后使用函数上移(350)将这个函数提升至超类。但构造函数的出现打乱了我的算盘,因为它们附加了特殊的规则,对一些做法与函数的调用次序有所限制。要对付它们,我需要略微不同的做法。

如果重构过程过于复杂,我会考虑转而使用以工厂函数取代构造函数(334)。

做法

如果超类还不存在构造函数,首先为其定义一个。确保让子类调用超类的构造函数。

使用移动语句(223)将子类中构造函数中的公共语句移动到超类的构造函数调用语句之后。

逐一移除子类间的公共代码,将其提升至超类构造函数中。对于公共代码中引用到的变量,将其作为参数传递给超类的构造函数。

测试。

如果存在无法简单提升至超类的公共代码,先应用提炼函数(106),再利用函数上移(350)提升之。

范例

我以下列“雇员”的例子开始:

class Party {}

class Employee extends Party {
 constructor(name, id, monthlyCost) {
  super();
  this._id = id;
  this._name = name;
  this._monthlyCost = monthlyCost;
 }
 // rest of class...
class Department extends Party {
 constructor(name, staff){
  super();
  this._name = name;
  this._staff = staff;
 }
 // rest of class...

Party 的两个子类间存在公共代码,也即是对名字(name)的赋值。我先用移动语句(223)将 Employee 中的这行赋值语句移动到 super()调用后面:

class Employee extends Party {
  constructor(name, id, monthlyCost) {
    super();
    this._name = name;
    this._id = id;
    this._monthlyCost = monthlyCost;
  }
  // rest of class...

测试。之后我将这行公共代码提升至超类的构造函数中。由于其中引用了一个子类构造函数传入的参数 name,于是我将该参数一并传给超类构造函数。

class Party...

constructor(name){
  this._name = name;
}

class Employee...

constructor(name, id, monthlyCost) {
  super(name);
  this._id = id;
  this._monthlyCost = monthlyCost;
}

class Department...

constructor(name, staff){
  super(name);
  this._staff = staff;
}

运行测试。然后大功告成。

多数时候,一个构造函数的工作原理都是这样:先(通过 super 调用)初始化共用的数据,再由各个子类完成额外的工作。但是,偶尔也需要将共用行为的初始化提升至超类,这时问题便来了。

请看下面的例子。

class Employee...

constructor (name) {...}

get isPrivileged() {...}

assignCar() {...}

class Manager extends Employee...

constructor(name, grade) {
  super(name);
  this._grade = grade;
  if (this.isPrivileged) this.assignCar(); // every subclass does this
}

get isPrivileged() {
  return this._grade >4;
}

这里我无法简单地提升 isPrivileged 函数至超类,因为调用它之前需要先为 grade 字段赋值,而该字段只能在子类的构造函数中初始化。

在这种场景下,我可以对这部分公共代码使用提炼函数(106)。

class Manager...

constructor(name, grade) {
  super(name);
  this._grade = grade;
  this.finishConstruction();
}

finishConstruction() {
  if (this.isPrivileged) this.assignCar();
}

然后再使用函数上移(350)将提炼得到的函数提升至超类。

class Employee...

finishConstruction() {
  if (this.isPrivileged) this.assignCar();
}

12.4 函数下移(Push Down Method)

反向重构:函数上移(350)

class Employee {
  get quota {...}
}

class Engineer extends Employee {...}
class Salesman extends Employee {...}


class Employee {...}
class Engineer extends Employee {...}
class Salesman extends Employee {
  get quota {...}
}

动机

如果超类中的某个函数只与一个(或少数几个)子类有关,那么最好将其从超类中挪走,放到真正关心它的子类中去。这项重构手法只有在超类明确知道哪些子类需要这个函数时适用。如果超类不知晓这个信息,那我就得用以多态取代条件表达式(272),只留些共用的行为在超类。

做法

将超类中的函数本体复制到每一个需要此函数的子类中。

删除超类中的函数。

测试。

将该函数从所有不需要它的那些子类中删除。

测试。

12.5 字段下移(Push Down Field)

反向重构:字段上移(353)

class Employee {   // Java
 private String quota;
}

class Engineer extends Employee {...}
class Salesman extends Employee {...}


class Employee {...}
class Engineer extends Employee {...}

class Salesman extends Employee {
 protected String quota;
}

动机

如果某个字段只被一个子类(或者一小部分子类)用到,就将其搬移到需要该字段的子类中。

做法

在所有需要该字段的子类中声明该字段。

将该字段从超类中移除。

测试。

将该字段从所有不需要它的那些子类中删掉。

测试。

12.6 以子类取代类型码(Replace Type Code with Subclasses)

包含旧重构:以 State/Strategy 取代类型码(Replace Type Code with State/Strategy)

包含旧重构:提炼子类(Extract Subclass)

反向重构:移除子类(369)

function createEmployee(name, type) {
  return new Employee(name, type);
}


function createEmployee(name, type) {
  switch (type) {
    case "engineer": return new Engineer(name);
    case "salesman": return new Salesman(name);
    case "manager": return new Manager (name);
}

动机

软件系统经常需要表现“相似但又不同的东西”,比如员工可以按职位分类(工程师、经理、销售),订单可以按优先级分类(加急、常规)。表现分类关系的第一种工具是类型码字段——根据具体的编程语言,可能实现为枚举、符号、字符串或者数字。类型码的取值经常来自给系统提供数据的外部服务。

大多数时候,有这样的类型码就够了。但也有些时候,我可以再多往前一步,引入子类。继承有两个诱人之处。首先,你可以用多态来处理条件逻辑。如果有几个函数都在根据类型码的取值采取不同的行为,多态就显得特别有用。引入子类之后,我可以用以多态取代条件表达式(272)来处理这些函数。

另外,有些字段或函数只对特定的类型码取值才有意义,例如“销售目标”只对“销售”这类员工才有意义。此时我可以创建子类,然后用字段下移(361)把这样的字段放到合适的子类中去。当然,我也可以加入验证逻辑,确保只有当类型码取值正确时才使用该字段,不过子类的形式能更明确地表达数据与类型之间的关系。

在使用以子类取代类型码时,我需要考虑一个问题:应该直接处理携带类型码的这个类,还是应该处理类型码本身呢?以前面的例子来说,我是应该让“工程师”成为“员工”的子类,还是应该在“员工”类包含“员工类别”属性、从后者继承出“工程师”和“经理”等子类型呢?直接的子类继承(前一种方案)比较简单,但职位类别就不能用在其他场合了。另外,如果员工的类别是可变的,那么也不能使用直接继承的方案。如果想在“员工类别”之下创建子类,可以运用以对象取代基本类型(174)把类型码包装成“员工类别”类,然后对其使用以子类取代类型码(362)。

做法

自封装类型码字段。

任选一个类型码取值,为其创建一个子类。覆写类型码类的取值函数,令其返回该类型码的字面量值。

创建一个选择器逻辑,把类型码参数映射到新的子类。

如果选择直接继承的方案,就用以工厂函数取代构造函数(334)包装构造函数,把选择器逻辑放在工厂函数里;如果选择间接继承的方案,选择器逻辑可以保留在构造函数里。

测试。

针对每个类型码取值,重复上述“创建子类、添加选择器逻辑”的过程。每次修改后执行测试。

去除类型码字段。

测试。

使用函数下移(359)和以多态取代条件表达式(272)处理原本访问了类型码的函数。全部处理完后,就可以移除类型码的访问函数。

范例

这个员工管理系统的例子已经被用烂了……

class Employee...

constructor(name, type){
  this.validateType(type);
  this._name = name;
  this._type = type;
}
validateType(arg) {
  if (!["engineer", "manager", "salesman"].includes(arg))
    throw new Error(`Employee cannot be of type ${arg}`);
}
toString() {return `${this._name} (${this._type})`;}

第一步是用封装变量(132)将类型码自封装起来。

class Employee...

get type() {return this._type;}
toString() {return `${this._name} (${this.type})`;}

请注意,toString 函数的实现中去掉了 this._type 的下划线,改用新建的取值函数了。

我选择从工程师("engineer")这个类型码开始重构。我打算采用直接继承的方案,也就是继承 Employee 类。子类很简单,只要覆写类型码的取值函数,返回适当的字面量值就行了。

class Engineer extends Employee {
  get type() {
    return "engineer";
  }
}

虽然 JavaScript 的构造函数也可以返回其他对象,但如果把选择器逻辑放在这儿,它会与字段初始化逻辑相互纠缠,搞得一团混乱。所以我会先运用以工厂函数取代构造函数(334),新建一个工厂函数以便安放选择器逻辑。

function createEmployee(name, type) {
  return new Employee(name, type);
}

然后我把选择器逻辑放在工厂函数中,从而开始使用新的子类。

function createEmployee(name, type) {
  switch (type) {
    case "engineer":
      return new Engineer(name, type);
  }
  return new Employee(name, type);
}

测试,确保一切运转正常。不过由于我的偏执,我随后会修改 Engineer 类中覆写的 type 函数,让它返回另外一个值,再次执行测试,确保会有测试失败,这样我才能肯定:新建的子类真的被用到了。然后我把 type 函数的返回值改回正确的状态,继续处理别的类型。我一次处理一个类型,每次修改后都执行测试。

class Salesman extends Employee {
  get type() {
    return "salesman";
  }
}

class Manager extends Employee {
  get type() {
    return "manager";
  }
}

function createEmployee(name, type) {
  switch (type) {
    case "engineer":
      return new Engineer(name, type);
    case "salesman":
      return new Salesman(name, type);
    case "manager":
      return new Manager(name, type);
  }
  return new Employee(name, type);
}

全部修改完成后,我就可以去掉类型码字段及其在超类中的取值函数(子类中的取值函数仍然保留)。

class Employee...

constructor(name, type){
 this.validateType(type);
 this._name = name;
 this._type = type;
}

get type() {return this._type;}
toString() {return `${this._name} (${this.type})`;}

测试,确保一切工作正常,我就可以移除验证逻辑,因为分发逻辑做的是同一回事。

class Employee...

constructor(name, type){
 this.validateType(type);
 this._name = name;
}
function createEmployee(name, type) {
 switch (type) {
  case "engineer": return new Engineer(name, type);
  case "salesman": return new Salesman(name, type);
  case "manager":  return new Manager (name, type);
  default: throw new Error(`Employee cannot be of type ${type}`);
 }
 return new Employee(name, type);
}

现在,构造函数的类型参数已经没用了,用改变函数声明(124)把它干掉。

class Employee...

constructor(name, type){
 this._name = name;
}

function createEmployee(name, type) {
 switch (type) {
  case "engineer": return new Engineer(name, type);
  case "salesman": return new Salesman(name, type);
  case "manager": return new Manager (name, type);
  default: throw new Error(`Employee cannot be of type ${type}`);
 }
}

子类中获取类型码的访问函数——get type 函数——仍然留着。通常我会希望把这些函数也干掉,不过可能需要多花点儿时间,因为有其他函数使用了它们。我会用以多态取代条件表达式(272)和函数下移(359)来处理这些访问函数。到某个时候,已经没有代码使用类型码的访问函数了,我再用移除死代码(237)给它们送终。

范例:使用间接继承

还是前面这个例子,我们回到最起初的状态,不过这次我已经有了“全职员工”和“兼职员工”两个子类,所以不能再根据员工类别代码创建子类了。另外,我可能需要允许员工类别动态调整,这也会导致不能使用直接继承的方案。

class Employee...

constructor(name, type){
 this.validateType(type);
 this._name = name;
 this._type = type;
}
validateType(arg) {
 if (!["engineer", "manager", "salesman"].includes(arg))
  throw new Error(`Employee cannot be of type ${arg}`);
}
get type()    {return this._type;}
set type(arg) {this._type = arg;}

get capitalizedType() {
 return this._type.charAt(0).toUpperCase() + this._type.substr(1).toLowerCase();
}
toString() {
 return `${this._name} (${this.capitalizedType})`;
}

这次的 toString 函数要更复杂一点,以便稍后展示用。

首先,我用以对象取代基本类型(174)包装类型码。

class EmployeeType {
  constructor(aString) {
    this._value = aString;
  }
  toString() {
    return this._value;
  }
}

class Employee...

constructor(name, type){
 this.validateType(type);
 this._name = name;
 this.type = type;
}
validateType(arg) {
 if (!["engineer", "manager", "salesman"].includes(arg))
  throw new Error(`Employee cannot be of type ${arg}`);
}
get typeString()  {return this._type.toString();}
get type()    {return this._type;}
set type(arg) {this._type = new EmployeeType(arg);}

get capitalizedType() {
 return this.typeString.charAt(0).toUpperCase()
  + this.typeString.substr(1).toLowerCase();
}
toString() {
 return `${this._name} (${this.capitalizedType})`;
}

然后使用以子类取代类型码(362)的老套路,把员工类别代码变成子类。

class Employee...

set type(arg) {this._type = Employee.createEmployeeType(arg);}

 static createEmployeeType(aString) {
  switch(aString) {
   case "engineer": return new Engineer();
   case "manager":  return new Manager ();
   case "salesman": return new Salesman();
   default: throw new Error(`Employee cannot be of type ${aString}`);
  }
 }

class EmployeeType {
}
class Engineer extends EmployeeType {
 toString() {return "engineer";}
}
class Manager extends EmployeeType {
 toString() {return "manager";}
}
class Salesman extends EmployeeType {
 toString() {return "salesman";}
}

如果重构到此为止的话,空的 EmployeeType 类可以去掉。但我更愿意留着它,用来明确表达各个子类之间的关系。并且有一个超类,也方便把其他行为搬移进去,例如我专门放在 toString 函数里的“名字大写”逻辑,就可以搬到超类。

class Employee...

toString() {
  return `${this._name} (${this.type.capitalizedName})`;
}

class EmployeeType...

get capitalizedName() {
return this.toString().charAt(0).toUpperCase()
  + this.toString().substr(1).toLowerCase();
}

熟悉本书第 1 版的读者大概能看出,这个例子来自第 1 版的以 State/Strategy 取代类型码重构手法。现在我认为这是以间接继承的方式使用以子类取代类型码,所以就不再将其作为一个单独的重构手法了。(而且我也一直不喜欢那个老重构手法的名字。)

12.7 移除子类(Remove Subclass)

曾用名:以字段取代子类(Replace Subclass with Fields)

反向重构:以子类取代类型码(362)

class Person {
  get genderCode() {
    return "X";
  }
}
class Male extends Person {
  get genderCode() {
    return "M";
  }
}
class Female extends Person {
  get genderCode() {
    return "F";
  }
}

class Person {
  get genderCode() {
    return this._genderCode;
  }
}

动机

子类很有用,它们为数据结构的多样和行为的多态提供支持,它们是针对差异编程的好工具。但随着软件的演化,子类所支持的变化可能会被搬移到别处,甚至完全去除,这时子类就失去了价值。有时添加子类是为了应对未来的功能,结果构想中的功能压根没被构造出来,或者用了另一种方式构造,使该子类不再被需要了。

子类存在着就有成本,阅读者要花心思去理解它的用意,所以如果子类的用处太少,就不值得存在了。此时,最好的选择就是移除子类,将其替换为超类中的一个字段。

做法

使用以工厂函数取代构造函数(334),把子类的构造函数包装到超类的工厂函数中。

如果构造函数的客户端用一个数组字段来决定实例化哪个子类,可以把这个判断逻辑放到超类的工厂函数中。

如果有任何代码检查子类的类型,先用提炼函数(106)把类型检查逻辑包装起来,然后用搬移函数(198)将其搬到超类。每次修改后执行测试。

新建一个字段,用于代表子类的类型。

将原本针对子类的类型做判断的函数改为使用新建的类型字段。

删除子类。

测试。

本重构手法常用于一次移除多个子类,此时需要先把这些子类都封装起来(添加工厂函数、搬移类型检查),然后再逐个将它们折叠到超类中。

范例

一开始,代码中遗留了两个子类。

class Person...

constructor(name) {
 this._name = name;
}
get name()    {return this._name;}
get genderCode() {return "X";}
// snip

class Male extends Person {
 get genderCode() {return "M";}
}

class Female extends Person {
 get genderCode() {return "F";}
}

如果子类就干这点儿事,那真的没必要存在。不过,在移除子类之前,通常有必要检查使用方代码是否有依赖于特定子类的行为,这样的行为需要被搬移到子类中。在这个例子里,我找到一些客户端代码基于子类的类型做判断,不过这也不足以成为保留子类的理由。

客户端...

const numberOfMales = people.filter(p => p instanceof Male).length;

每当想要改变某个东西的表现形式时,我会先将当下的表现形式封装起来,从而尽量减小对客户端代码的影响。对于“创建子类对象”而言,封装的方式就是以工厂函数取代构造函数(334)。在这里,实现工厂有两种方式。

最直接的方式是为每个构造函数分别创建一个工厂函数。

function createPerson(name) {
  return new Person(name);
}
function createMale(name) {
  return new Male(name);
}
function createFemale(name) {
  return new Female(name);
}

虽然这是最直接的选择,但这样的对象经常是从输入源加载出来,直接根据性别代码创建对象。

function loadFromInput(data) {
 const result = [];
 data.forEach(aRecord => {
  let p;
  switch (aRecord.gender) {
   case 'M': p = new Male(aRecord.name); break;
   case 'F': p = new Female(aRecord.name); break;
   default: p = new Person(aRecord.name);
  }
  result.push(p);
 });
 return result;
}

有鉴于此,我觉得更好的办法是先用提炼函数(106)把“选择哪个类来实例化”的逻辑提炼成工厂函数。

function createPerson(aRecord) {
 let p;
 switch (aRecord.gender) {
  case 'M': p = new Male(aRecord.name); break;
  case 'F': p = new Female(aRecord.name); break;
  default: p = new Person(aRecord.name);
 }
 return p;
}
function loadFromInput(data) {
 const result = [];
 data.forEach(aRecord => {
  result.push(createPerson(aRecord));
 });
 return result;
}

提炼完工厂函数后,我会对这两个函数做些清理。先用内联变量(123)简化 createPerson 函数:

function createPerson(aRecord) {
  switch (aRecord.gender) {
    case "M":
      return new Male(aRecord.name);
    case "F":
      return new Female(aRecord.name);
    default:
      return new Person(aRecord.name);
  }
}

再用以管道取代循环(231)简化 loadFromInput 函数:

function loadFromInput(data) {
  return data.map(aRecord => createPerson(aRecord));
}

工厂函数封装了子类的创建逻辑,但代码中还有一处用到 instanceof 运算符——这从来不会是什么好味道。我用提炼函数(106)把这个类型检查逻辑提炼出来。

客户端...

const numberOfMales = people.filter(p => isMale(p)).length;

function isMale(aPerson) {return aPerson instanceof Male;}

然后用搬移函数(198)将其移到 Person 类。

class Person...

get isMale() {return this instanceof Male;}

客户端...

const numberOfMales = people.filter(p => p.isMale).length;

重构到这一步,所有与子类相关的知识都已经安全地包装在超类和工厂函数中。(对于“超类引用子类”这种情况,通常我会很警惕,不过这段代码用不了一杯茶的工夫就会被干掉,所以也不用太担心。)

现在,添加一个字段来表示子类之间的差异。既然有来自别处的一个类型代码,直接用它也无妨。

class Person...

constructor(name, genderCode) {
  this._name = name;
  this._genderCode = genderCode || "X";
}

get genderCode() {return this._genderCode;}

在初始化时先将其设置为默认值。(顺便说一句,虽然大多数人可以归类为男性或女性,但确实有些人不是这两种性别中的任何一种。忽视这些人的存在,是一个常见的建模错误。)

首先从“男性”的情况开始,将相关逻辑折叠到超类中。为此,首先要修改工厂函数,令其返回一个 Person 对象,然后修改所有 instanceof 检查逻辑,改为使用性别代码字段。

function createPerson(aRecord) {
  switch (aRecord.gender) {
    case "M":
      return new Person(aRecord.name, "M");
    case "F":
      return new Female(aRecord.name);
    default:
      return new Person(aRecord.name);
  }
}

class Person...

get isMale() {return "M" === this._genderCode;}

此时我可以测试,删除 Male 子类,再次测试,然后对 Female 子类也如法炮制。

function createPerson(aRecord) {
  switch (aRecord.gender) {
    case "M":
      return new Person(aRecord.name, "M");
    case "F":
      return new Person(aRecord.name, "F");
    default:
      return new Person(aRecord.name);
  }
}

类型代码的分配有点儿失衡,默认情况没有类型代码,这种情况让我很烦心。未来阅读代码的人会一直好奇背后的原因。所以我更愿意现在做点儿修改,给所有情况都平等地分配类型代码——只要不会引入额外的复杂性就好。

function createPerson(aRecord) {
  switch (aRecord.gender) {
    case "M":
      return new Person(aRecord.name, "M");
    case "F":
      return new Person(aRecord.name, "F");
    default:
      return new Person(aRecord.name, "X");
  }
}

class Person...

constructor(name, genderCode) {
  this._name = name;
  this._genderCode = genderCode || "X";
}

12.8 提炼超类(Extract Superclass)

class Department {
 get totalAnnualCost() {...}
 get name() {...}
 get headCount() {...}
}

class Employee {
 get annualCost() {...}
 get name() {...}
 get id() {...}
}


class Party {
 get name() {...}
 get annualCost() {...}
}

class Department extends Party {
 get annualCost() {...}
 get headCount() {...}
}

class Employee extends Party {
 get annualCost() {...}
 get id() {...}
}

动机

如果我看见两个类在做相似的事,可以利用基本的继承机制把它们的相似之处提炼到超类。我可以用字段上移(353)把相同的数据搬到超类,用函数上移(350)搬移相同的行为。

很多技术作家在谈到面向对象时,认为继承必须预先仔细计划,应该根据“真实世界”的分类结构建立对象模型。真实世界的分类结构可以作为设计继承关系的提示,但还有很多时候,合理的继承关系是在程序演化的过程中才浮现出来的:我发现了一些共同元素,希望把它们抽取到一处,于是就有了继承关系。

另一种选择就是提炼类(182)。这两种方案之间的选择,其实就是继承和委托之间的选择,总之目的都是把重复的行为收拢一处。提炼超类通常是比较简单的做法,所以我会首选这个方案。即便选错了,也总有以委托取代超类(399)这瓶后悔药可吃。

做法

为原本的类新建一个空白的超类。

如果需要的话,用改变函数声明(124)调整构造函数的签名。

测试。

使用构造函数本体上移(355)、函数上移(350)和字段上移(353)手法,逐一将子类的共同元素上移到超类。

检查留在子类中的函数,看它们是否还有共同的成分。如果有,可以先用提炼函数(106)将其提炼出来,再用函数上移(350)搬到超类。

检查所有使用原本的类的客户端代码,考虑将其调整为使用超类的接口。

范例

下面这两个类,仔细考虑之下,是有一些共同之处的——它们都有名字(name),也都有月度成本(monthly cost)和年度成本(annual cost)的概念:

class Employee {
 constructor(name, id, monthlyCost) {
  this._id = id;
  this._name = name;
  this._monthlyCost = monthlyCost;
 }
 get monthlyCost() {return this._monthlyCost;}
 get name() {return this._name;}
 get id() {return this._id;}

 get annualCost() {
  return this.monthlyCost * 12;
 }
}

class Department {
 constructor(name, staff){
  this._name = name;
  this._staff = staff;
 }
 get staff() {return this._staff.slice();}
 get name() {return this._name;}

 get totalMonthlyCost() {
  return this.staff
   .map(e => e.monthlyCost)
   .reduce((sum, cost) => sum + cost);
 }
 get headCount() {
  return this.staff.length;
 }
 get totalAnnualCost() {
  return this.totalMonthlyCost * 12;
 }
}

可以为它们提炼一个共同的超类,更明显地表达出它们之间的共同行为。

首先创建一个空的超类,让原来的两个类都继承这个新的类。

class Party {}

class Employee extends Party {
 constructor(name, id, monthlyCost) {
  super();
  this._id = id;
  this._name = name;
  this._monthlyCost = monthlyCost;
 }
 // rest of class...
class Department extends Party {
 constructor(name, staff){
  super();
  this._name = name;
  this._staff = staff;
 }
 // rest of class...

在提炼超类时,我喜欢先从数据开始搬移,在 JavaScript 中就需要修改构造函数。我先用字段上移(353)把 name 字段搬到超类中。

class Party...

constructor(name){
  this._name = name;
}

class Employee...

constructor(name, id, monthlyCost) {
  super(name);
  this._id = id;
  this._monthlyCost = monthlyCost;
}

class Department...

constructor(name, staff){
  super(name);
  this._staff = staff;
}

把数据搬到超类的同时,可以用函数上移(350)把相关的函数也一起搬移。首先是 name 函数:

class Party...

get name() {return this._name;}

class Employee...

get name() {return this._name;}

class Department...

get name() {return this._name;}

有两个函数实现非常相似。

class Employee...

get annualCost() {
  return this.monthlyCost * 12;
}

class Department...

get totalAnnualCost() {
  return this.totalMonthlyCost * 12;
}

它们各自使用的函数 monthlyCost 和 totalMonthlyCost 名字和实现都不同,但意图却是一致。我可以用改变函数声明(124)将它们的名字统一。

class Department...

get totalAnnualCost() {
  return this.monthlyCost * 12;
}

get monthlyCost() { ... }

然后对计算年度成本的函数也做相似的改名:

class Department...

get annualCost() {
  return this.monthlyCost * 12;
}

现在可以用函数上移(350)把这个函数搬到超类了。

class Party...

get annualCost() {
  return this.monthlyCost * 12;
}

class Employee...

get annualCost() {
  return this.monthlyCost * 12;
}

class Department...

get annualCost() {
  return this.monthlyCost * 12;
}

12.9 折叠继承体系(Collapse Hierarchy)

class Employee {...}
class Salesman extends Employee {...}


class Employee {...}

动机

在重构类继承体系时,我经常把函数和字段上下移动。随着继承体系的演化,我有时会发现一个类与其超类已经没多大差别,不值得再作为独立的类存在。此时我就会把超类和子类合并起来。

做法

选择想移除的类:是超类还是子类?

我选择的依据是看哪个类的名字放在未来更有意义。如果两个名字都不够好,我就随便挑一个。

使用字段上移(353)、字段下移(361)、函数上移(350)和函数下移(359),把所有元素都移到同一个类中。

调整即将被移除的那个类的所有引用点,令它们改而引用合并后留下的类。

移除我们的目标;此时它应该已经成为一个空类。

测试。

12.10 以委托取代子类(Replace Subclass with Delegate)

class Order {
  get daysToShip() {
    return this._warehouse.daysToShip;
  }
}

class PriorityOrder extends Order {
  get daysToShip() {
    return this._priorityPlan.daysToShip;
  }
}

class Order {
  get daysToShip() {
    return this._priorityDelegate
      ? this._priorityDelegate.daysToShip
      : this._warehouse.daysToShip;
  }
}

class PriorityOrderDelegate {
  get daysToShip() {
    return this._priorityPlan.daysToShip;
  }
}

动机

如果一个对象的行为有明显的类别之分,继承是很自然的表达方式。我可以把共用的数据和行为放在超类中,每个子类根据需要覆写部分特性。在面向对象语言中,继承很容易实现,因此也是程序员熟悉的机制。

但继承也有其短板。最明显的是,继承这张牌只能打一次。导致行为不同的原因可能有多种,但继承只能用于处理一个方向上的变化。比如说,我可能希望“人”的行为根据“年龄段”不同,并且根据“收入水平”不同。使用继承的话,子类可以是“年轻人”和“老人”,也可以是“富人”和“穷人”,但不能同时采用两种继承方式。

更大的问题在于,继承给类之间引入了非常紧密的关系。在超类上做任何修改,都很可能破坏子类,所以我必须非常小心,并且充分理解子类如何从超类派生。如果两个类的逻辑分处不同的模块、由不同的团队负责,问题就会更麻烦。

这两个问题用委托都能解决。对于不同的变化原因,我可以委托给不同的类。委托是对象之间常规的关系。与继承关系相比,使用委托关系时接口更清晰、耦合更少。因此,继承关系遇到问题时运用以委托取代子类是常见的情况。

有一条流行的原则:“对象组合优于类继承”(“组合”跟“委托”是同一回事)。很多人把这句话解读为“继承有害”,并因此声称绝不应该使用继承。我经常使用继承,部分是因为我知道,如果稍后需要改变,我总可以使用以委托取代子类。继承是一种很有价值的机制,大部分时候能达到效果,不会带来问题。所以我会从继承开始,如果开始出现问题,再转而使用委托。这种用法与前面说的原则实际上是一致的——这条出自名著《设计模式》[gof]的原则解释了如何让继承和组合协同工作。这条原则之所以强调“组合优于继承”,其实是对彼时继承常被滥用的回应。

熟悉《设计模式》一书的读者可以这样来理解本重构手法,就是用状态(State)模式或者策略(Strategy)模式取代子类。这两个模式在结构上是相同的,都是由宿主对象把责任委托给另一个继承体系。以委托取代子类并非总会需要建立一个继承体系来接受委托(下面第一个例子就没有),不过建立一个状态或策略的继承体系经常都是有用的。

做法

如果构造函数有多个调用者,首先用以工厂函数取代构造函数(334)把构造函数包装起来。

创建一个空的委托类,这个类的构造函数应该接受所有子类特有的数据项,并且经常以参数的形式接受一个指回超类的引用。

在超类中添加一个字段,用于安放委托对象。

修改子类的创建逻辑,使其初始化上述委托字段,放入一个委托对象的实例。

这一步可以在工厂函数中完成,也可以在构造函数中完成(如果构造函数有足够的信息以创建正确的委托对象的话)。

选择一个子类中的函数,将其移入委托类。

使用搬移函数(198)手法搬移上述函数,不要删除源类中的委托代码。

如果这个方法用到的其他元素也应该被移入委托对象,就把它们一并搬移。如果它用到的元素应该留在超类中,就在委托对象中添加一个字段,令其指向超类的实例。

如果被搬移的源函数还在子类之外被调用了,就把留在源类中的委托代码从子类移到超类,并在委托代码之前加上卫语句,检查委托对象存在。如果子类之外已经没有其他调用者,就用移除死代码(237)去掉已经没人使用的委托代码。

如果有多个委托类,并且其中的代码出现了重复,就使用提炼超类(375)手法消除重复。此时如果默认行为已经被移入了委托类的超类,源超类的委托函数就不再需要卫语句了。

测试。

重复上述过程,直到子类中所有函数都搬到委托类。

找到所有调用子类构造函数的地方,逐一将其改为使用超类的构造函数。

测试。

运用移除死代码(237)去掉子类。

范例

下面这个类用于处理演出(show)的预订(booking)。

class Booking...

constructor(show, date) {
  this._show = show;
  this._date = date;
}

它有一个子类,专门用于预订高级(premium)票,这个子类要考虑各种附加服务(extra)。

class PremiumBooking extends Booking...

constructor(show, date, extras) {
  super(show, date);
  this._extras = extras;
}

PremiumBooking 类在超类基础上做了好些改变。在这种“针对差异编程”(programming-by-difference)的风格中,子类常会覆写超类的方法,有时还会添加只对子类有意义的新方法。我不打算讨论所有差异点,只选几处有意思的案例来分析。

先来看一处简单的覆写。常规票在演出结束后会有“对话创作者”环节(talkback),但只在非高峰日提供这项服务。

class Booking...

get hasTalkback() {
 return this._show.hasOwnProperty('talkback') && !this.isPeakDay;
}

PremiumBooking 覆写了这个逻辑,任何一天都提供与创作者的对话。

class PremiumBooking...

get hasTalkback() {
  return this._show.hasOwnProperty('talkback');
}

定价逻辑也是相似的覆写,不过略有不同:PremiumBooking 调用了超类中的方法。

class Booking...

get basePrice() {
  let result = this._show.price;
  if (this.isPeakDay) result += Math.round(result * 0.15);
  return result;
}

class PremiumBooking...

get basePrice() {
  return Math.round(super.basePrice + this._extras.premiumFee);
}

最后一个例子是 PremiumBooking 提供了一个超类中没有的行为。

class PremiumBooking...

get hasDinner() {
  return this._extras.hasOwnProperty('dinner') && !this.isPeakDay;
}

继承在这个例子中工作良好。即使不了解子类,我同样也可以理解超类的逻辑。子类只描述自己与超类的差异——既避免了重复,又清晰地表述了自己引入的差异。

说真的,它也并非如此完美。超类的一些结构只在特定的子类存在时才有意义——有些函数的组织方式完全就是为了方便覆写特定类型的行为。所以,尽管大部分时候我可以修改超类而不必理解子类,但如果刻意不关注子类的存在,在修改超类时偶尔有可能会破坏子类。不过,如果这种“偶尔”发生得不太频繁,继承就还是划算的——只要我有良好的测试,当子类被破坏时就能及时发现。

那么,既然情况还算不坏,为什么我想用以委托取代子类来做出改变呢?因为继承只能使用一次,如果我有别的原因想使用继承,并且这个新的原因比“高级预订”更有必要,就需要换一种方式来处理高级预订。另外,我可能需要动态地把普通预订升级成高级预订,例如提供 aBooking.bePremium()这样一个函数。有时我可以新建一个对象(就好像通过 HTTP 请求从服务器端加载全新的数据),从而避免“对象本身升级”的问题。但有时我需要修改数据本身的结构,而不重建整个数据结构。如果一个 Booking 对象被很多地方引用,也很难将其整个替换掉。此时,就有必要允许在“普通预订”和“高级预订”之间来回转换。

当这样的需求积累到一定程度时,我就该使用以委托取代子类了。现在客户端直接调用两个类的构造函数来创建不同的预订。

进行普通预订的客户端

aBooking = new Booking(show, date);

进行高级预订的客户端

aBooking = new PremiumBooking(show, date, extras);

去除子类会改变对象创建的方式,所以我要先用以工厂函数取代构造函数(334)把构造函数封装起来。

顶层作用域...

function createBooking(show, date) {
  return new Booking(show, date);
}
function createPremiumBooking(show, date, extras) {
  return new PremiumBooking(show, date, extras);
}

进行普通预订的客户端

aBooking = createBooking(show, date);

进行高级预订的客户端

aBooking = createPremiumBooking(show, date, extras);

然后新建一个委托类。这个类的构造函数参数有两部分:首先是指向 Booking 对象的反向引用,随后是只有子类才需要的那些数据。我需要传入反向引用,是因为子类的几个函数需要访问超类中的数据。有继承关系的时候,访问这些数据很容易;而在委托关系中,就得通过反向引用来访问。

class PremiumBookingDelegate...

constructor(hostBooking, extras) {
  this._host = hostBooking;
  this._extras = extras;
}

现在可以把新建的委托对象与 Booking 对象关联起来。在“创建高级预订”的工厂函数中修改即可。

顶层作用域...

function createPremiumBooking(show, date, extras) {
  const result = new PremiumBooking(show, date, extras);
  result._bePremium(extras);
  return result;
}

class Booking...

_bePremium(extras) {
  this._premiumDelegate = new PremiumBookingDelegate(this, extras);
}

_bePremium 函数以下划线开头,表示这个函数不应该被当作 Booking 类的公共接口。当然,如果最终我们希望允许普通预订转换成高级预订,这个函数也可以成为公共接口。

或者我也可以在 Booking 类的构造函数中构建它与委托对象之间的联系。为此,我需要以某种方式告诉构造函数“这是一个高级预订”:可以通过一个额外的参数,也可以直接通过 extras 参数来表示(如果我能确定这个参数只有高级预订才会用到的话)。不过我还是更愿意在工厂函数中构建这层联系,因为这样可以把意图表达得更明确。

结构设置好了,现在该动手搬移行为了。我首先考虑 hasTalkback 函数简单的覆写逻辑。现在的代码如下。

class Booking...

get hasTalkback() {
  return this._show.hasOwnProperty('talkback') && !this.isPeakDay;
}

class PremiumBooking...

get hasTalkback() {
  return this._show.hasOwnProperty('talkback');
}

我用搬移函数(198)把子类中的函数搬到委托类中。为了让它适应新家,原本访问超类中数据的代码,现在要改为调用_host 对象。

class PremiumBookingDelegate...

get hasTalkback() {
  return this._host._show.hasOwnProperty('talkback');
}

class PremiumBooking...

get hasTalkback() {
  return this._premiumDelegate.hasTalkback;
}

测试,确保一切正常,然后把子类中的函数删掉:

class PremiumBooking...

get hasTalkback() {
  return this._premiumDelegate.hasTalkback;
}

再次测试,现在应该有一些测试失败,因为原本有些代码会用到子类上的 hasTalkback 函数。

现在我要修复这些失败的测试:在超类的函数中添加适当的分发逻辑,如果有代理对象存在就使用代理对象。这样,这一步重构就算完成了。

class Booking...

get hasTalkback() {
  return (this._premiumDelegate)
    ? this._premiumDelegate.hasTalkback
    : this._show.hasOwnProperty('talkback') && !this.isPeakDay;
}

下一个要处理的是 basePrice 函数。

class Booking...

get basePrice() {
  let result = this._show.price;
  if (this.isPeakDay) result += Math.round(result * 0.15);
  return result;
}

class PremiumBooking...

get basePrice() {
  return Math.round(super.basePrice + this._extras.premiumFee);
}

情况大致相同,但有一点儿小麻烦:子类中调用了超类中的同名函数(在这种“子类扩展超类行为”的用法中,这种情况很常见)。把子类的代码移到委托类时,需要继续调用超类的逻辑——但我不能直接调用 this._host.basePrice,这会导致无穷递归,因为 _host 对象就是 PremiumBooking 对象自己。

有两个办法来处理这个问题。一种办法是,可以用提炼函数(106)把“基本价格”的计算逻辑提炼出来,从而把分发逻辑与价格计算逻辑拆开。(剩下的操作就跟前面的例子一样了。)

class Booking...

get basePrice() {
 return (this._premiumDelegate)
  ? this._premiumDelegate.basePrice
  : this._privateBasePrice;
}

get _privateBasePrice() {
 let result = this._show.price;
 if (this.isPeakDay) result += Math.round(result * 0.15);
 return result;
}

class PremiumBookingDelegate...

get basePrice() {
  return Math.round(this._host._privateBasePrice + this._extras.premiumFee);
}

另一种办法是,可以重新定义委托对象中的函数,使其成为基础函数的扩展。

class Booking...

get basePrice() {
  let result = this._show.price;
  if (this.isPeakDay) result += Math.round(result * 0.15);
  return (this._premiumDelegate)
    ? this._premiumDelegate.extendBasePrice(result)
    : result;
}

class PremiumBookingDelegate...

extendBasePrice(base) {
  return Math.round(base + this._extras.premiumFee);
}

两种办法都可行,我更偏爱后者一点儿,因为需要的代码较少。

最后一个例子是一个只存在于子类中的函数。

class PremiumBooking...

get hasDinner() {
  return this._extras.hasOwnProperty('dinner') && !this.isPeakDay;
}

我把它从子类移到委托类。

class PremiumBookingDelegate...

get hasDinner() {
  return this._extras.hasOwnProperty('dinner') && !this._host.isPeakDay;
}

然后在 Booking 类中添加分发逻辑。

class Booking...

get hasDinner() {
  return (this._premiumDelegate)
    ? this._premiumDelegate.hasDinner
    : undefined;
}

在 JavaScript 中,如果尝试访问一个没有定义的属性,就会得到 undefined,所以我在这个函数中也这样做。(尽管我直觉认为应该抛出错误,我所熟悉的其他面向对象动态语言就是这样做的。)

所有的行为都从子类中搬移出去之后,我就可以修改工厂函数,令其返回超类的实例。再次运行测试,确保一切都运转良好,然后我就可以删除子类。

顶层作用域...

function createPremiumBooking(show, date, extras) {
  const result = new PremiumBooking(show, date, extras);
  result._bePremium(extras);
  return result;
}

class PremiumBooking extends Booking ...

只看这个重构本身,我并不觉得代码质量得到了提升。继承原本很好地应对了需求场景,换成委托以后,我增加了分发逻辑、双向引用,复杂度上升不少。不过这个重构可能还是值得的,因为现在“是否高级预订”这个状态可以改变了,并且我也可以用继承来达成其他目的了。如果有这些需求的话,去除原有的继承关系带来的损失可能还是划算的。

范例:取代继承体系

前面的例子展示了如何用以委托取代子类去除单个子类。还可以用这个重构手法去除整个继承体系。

function createBird(data) {
 switch (data.type) {
  case 'EuropeanSwallow':
   return new EuropeanSwallow(data);
  case 'AfricanSwallow':
   return new AfricanSwallow(data);
  case 'NorweigianBlueParrot':
   return new NorwegianBlueParrot(data);
  default:
   return new Bird(data);
 }
}

class Bird {
 constructor(data) {
  this._name = data.name;
  this._plumage = data.plumage;
 }
 get name()  {return this._name;}

 get plumage() {
  return this._plumage || "average";
 }
 get airSpeedVelocity() {return null;}
}

class EuropeanSwallow extends Bird {
 get airSpeedVelocity() {return 35;}
}

class AfricanSwallow extends Bird {
 constructor(data) {
  super (data);
  this._numberOfCoconuts = data.numberOfCoconuts;
 }
 get airSpeedVelocity() {
  return 40 - 2 * this._numberOfCoconuts;
 }
}

class NorwegianBlueParrot extends Bird {
 constructor(data) {
  super (data);
  this._voltage = data.voltage;
  this._isNailed = data.isNailed;
 }

 get plumage() {
  if (this._voltage > 100) return "scorched";
  else return this._plumage || "beautiful";
 }
 get airSpeedVelocity() {
  return (this._isNailed) ? 0 : 10 + this._voltage / 10;
 }
}

上面这个关于鸟儿(bird)的系统很快要有一个大变化:有些鸟是“野生的”(wild),有些鸟是“家养的”(captive),两者之间的行为会有很大差异。这种差异可以建模为 Bird 类的两个子类:WildBird 和 CaptiveBird。但继承只能用一次,所以如果想用子类来表现“野生”和“家养”的差异,就得先去掉关于“不同品种”的继承关系。

在涉及多个子类时,我会一次处理一个子类,先从简单的开始——在这里,最简单的当属 EuropeanSwallow(欧洲燕)。我先给它建一个空的委托类。

class EuropeanSwallowDelegate {}

委托类中暂时还没有传入任何数据或反向引用。在这个例子里,我会在需要时再引入这些参数。

现在需要决定如何初始化委托字段。由于构造函数接受的唯一参数 data 包含了所有的信息,我决定在构造函数中初始化委托字段。考虑到有多个委托对象要添加,我会建一个函数,其中根据类型码(data.type)来选择适当的委托对象。

class Bird...

constructor(data) {
 this._name = data.name;
 this._plumage = data.plumage;
 this._speciesDelegate = this.selectSpeciesDelegate(data);
}

 selectSpeciesDelegate(data) {
  switch(data.type) {
   case 'EuropeanSwallow':
    return new EuropeanSwallowDelegate();
   default: return null;
  }
 }

结构设置完毕,我可以用搬移函数(198)把 EuropeanSwallow 的 airSpeedVelocity 函数搬到委托对象中。

class EuropeanSwallowDelegate...

get airSpeedVelocity() {return 35;}

class EuropeanSwallow...

get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}

修改超类的 airSpeedVelocity 函数,如果发现有委托对象存在,就调用之。

class Bird...

get airSpeedVelocity() {
  return this._speciesDelegate ? this._speciesDelegate.airSpeedVelocity : null;
}

然后,删除子类。

class EuropeanSwallow extends Bird {
  get airSpeedVelocity() {
    return this._speciesDelegate.airSpeedVelocity;
  }
}

顶层作用域...

function createBird(data) {
  switch (data.type) {
    case "EuropeanSwallow":
      return new EuropeanSwallow(data);
    case "AfricanSwallow":
      return new AfricanSwallow(data);
    case "NorweigianBlueParrot":
      return new NorwegianBlueParrot(data);
    default:
      return new Bird(data);
  }
}

接下来处理 AfricanSwallow(非洲燕)子类。为它创建一个委托类,这次委托类的构造函数需要传入 data 参数。

class AfricanSwallowDelegate...

constructor(data) {
  this._numberOfCoconuts = data.numberOfCoconuts;
}

class Bird…

selectSpeciesDelegate(data) {
 switch(data.type) {
  case 'EuropeanSwallow':
   return new EuropeanSwallowDelegate();
  case 'AfricanSwallow':
   return new AfricanSwallowDelegate(data);
  default: return null;
 }
}

同样用搬移函数(198)把 airSpeedVelocity 搬到委托类中。

class AfricanSwallowDelegate...

get airSpeedVelocity() {
  return 40 - 2 * this._numberOfCoconuts;
}

class AfricanSwallow...

get airSpeedVelocity() {
  return this._speciesDelegate.airSpeedVelocity;
}

再删掉 AfricanSwallow 子类。

class AfricanSwallow extends Bird {
  // all of the body ...
}

function createBird(data) {
  switch (data.type) {
    case "AfricanSwallow":
      return new AfricanSwallow(data);
    case "NorweigianBlueParrot":
      return new NorwegianBlueParrot(data);
    default:
      return new Bird(data);
  }
}

接下来是 NorwegianBlueParrot(挪威蓝鹦鹉)子类。创建委托类和搬移 airSpeed Velocity 函数的步骤都跟前面一样,所以我直接展示结果好了。

class Bird...

selectSpeciesDelegate(data) {
 switch(data.type) {
  case 'EuropeanSwallow':
   return new EuropeanSwallowDelegate();
  case 'AfricanSwallow':
   return new AfricanSwallowDelegate(data);
  case 'NorweigianBlueParrot':
   return new NorwegianBlueParrotDelegate(data);
  default: return null;
 }
}

class NorwegianBlueParrotDelegate...

constructor(data) {
  this._voltage = data.voltage;
  this._isNailed = data.isNailed;
}
get airSpeedVelocity() {
  return (this._isNailed) ? 0 : 10 + this._voltage / 10;
}

一切正常。但 NorwegianBlueParrot 还覆写了 plumage 属性,前面两个例子则没有。首先我还是用搬移函数(198)把 plumage 函数搬到委托类中,这一步不难,不过需要修改构造函数,放入对 Bird 对象的反向引用。

class NorwegianBlueParrot...

get plumage() {
  return this._speciesDelegate.plumage;
}

class NorwegianBlueParrotDelegate...

get plumage() {
 if (this._voltage > 100) return "scorched";
 else return this._bird._plumage || "beautiful";
}

constructor(data, bird) {
 this._bird = bird;
 this._voltage = data.voltage;
 this._isNailed = data.isNailed;
}

class Bird...

selectSpeciesDelegate(data) {
 switch(data.type) {
  case 'EuropeanSwallow':
   return new EuropeanSwallowDelegate();
  case 'AfricanSwallow':
   return new AfricanSwallowDelegate(data);
  case 'NorweigianBlueParrot':
   return new NorwegianBlueParrotDelegate(data, this);
  default: return null;
 }
}

麻烦之处在于如何去掉子类中的 plumage 函数。如果我像下面这么干就会得到一大堆错误,因为其他品种的委托类没有 plumage 这个属性。

class Bird...

get plumage() {
  if (this._speciesDelegate)
    return this._speciesDelegate.plumage;
  else
    return this._plumage || "average";
}

我可以做一个更明确的条件分发:

class Bird...

get plumage() {
  if (this._speciesDelegate instanceof NorwegianBlueParrotDelegate)
    return this._speciesDelegate.plumage;
  else
    return this._plumage || "average";
}

不过我超级反感这种做法,希望你也能闻出同样的坏味道。像这样的显式类型检查几乎总是坏主意。

另一个办法是在其他委托类中实现默认的行为。

class Bird...

get plumage() {
  if (this._speciesDelegate)
    return this._speciesDelegate.plumage;
  else
    return this._plumage || "average";
}

class EuropeanSwallowDelegate...

get plumage() {
  return this._bird._plumage || "average";
}

class AfricanSwallowDelegate...

get plumage() {
  return this._bird._plumage || "average";
}

但这又造成了 plumage 默认行为的重复。如果这还不够糟糕的话,还有一个“额外奖励”:构造函数中给_bird 反向引用赋值的代码也会重复。

解决重复的办法,很自然,就是继承——用提炼超类(375)从各个代理类中提炼出一个共同继承的超类。

class SpeciesDelegate {
 constructor(data, bird) {
  this._bird = bird;
 }
 get plumage() {
  return this._bird._plumage || "average";
 }

class EuropeanSwallowDelegate extends SpeciesDelegate {

class AfricanSwallowDelegate extends SpeciesDelegate {
 constructor(data, bird) {
  super(data,bird);
  this._numberOfCoconuts = data.numberOfCoconuts;
}

class NorwegianBlueParrotDelegate extends SpeciesDelegate {
 constructor(data, bird) {
  super(data, bird);
  this._voltage = data.voltage;
  this._isNailed = data.isNailed;
}

有了共同的超类以后,就可以把 SpeciesDelegate 字段默认设置为这个超类的实例,并把 Bird 类中的默认行为搬移到 SpeciesDelegate 超类中。

class Bird...

selectSpeciesDelegate(data) {
 switch(data.type) {
  case 'EuropeanSwallow':
   return new EuropeanSwallowDelegate(data, this);
  case 'AfricanSwallow':
   return new AfricanSwallowDelegate(data, this);
  case 'NorweigianBlueParrot':
   return new NorwegianBlueParrotDelegate(data, this);
  default: return new SpeciesDelegate(data, this);
 }
}
// rest of bird’s code...

get plumage() {return this._speciesDelegate.plumage;}

get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}

class SpeciesDelegate...

get airSpeedVelocity() {return null;}

我喜欢这种办法,因为它简化了 Bird 类中的委托函数。我可以一目了然地看到哪些行为已经被委托给 SpeciesDelegate,哪些行为还留在 Bird 类中。

这几个类最终的状态如下:

function createBird(data) {
 return new Bird(data);
}
class Bird {
 constructor(data) {
  this._name = data.name;
  this._plumage = data.plumage;
  this._speciesDelegate = this.selectSpeciesDelegate(data);
 }
 get name()    {return this._name;}
 get plumage() {return this._speciesDelegate.plumage;}
 get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}

 selectSpeciesDelegate(data) {
  switch(data.type) {
   case 'EuropeanSwallow':
    return new EuropeanSwallowDelegate(data, this);
   case 'AfricanSwallow':
    return new AfricanSwallowDelegate(data, this);
   case 'NorweigianBlueParrot':
    return new NorwegianBlueParrotDelegate(data, this);
   default: return new SpeciesDelegate(data, this);
  }
 }
 // rest of bird’s code...
}

class SpeciesDelegate {
 constructor(data, bird) {
  this._bird = bird;
 }
 get plumage() {
  return this._bird._plumage || "average";
 }
 get airSpeedVelocity() {return null;}
}

class EuropeanSwallowDelegate extends SpeciesDelegate {
 get airSpeedVelocity() {return 35;}
}

class AfricanSwallowDelegate extends SpeciesDelegate {
 constructor(data, bird) {
  super(data,bird);
  this._numberOfCoconuts = data.numberOfCoconuts;
 }
 get airSpeedVelocity() {
  return 40 - 2 * this._numberOfCoconuts;
 }
}

class NorwegianBlueParrotDelegate extends SpeciesDelegate {
 constructor(data, bird) {
  super(data, bird);
  this._voltage = data.voltage;
  this._isNailed = data.isNailed;
 }
 get airSpeedVelocity() {
  return (this._isNailed) ? 0 : 10 + this._voltage / 10;
 }
 get plumage() {
  if (this._voltage > 100) return "scorched";
  else return this._bird._plumage || "beautiful";
 }
}

在这个例子中,我用一系列委托类取代了原来的多个子类,与原来非常相似的继承结构被转移到了 SpeciesDelegate 下面。除了给 Bird 类重新被继承的机会,从这个重构中我还有什么收获?新的继承体系范围更收拢了,只涉及各个品种不同的数据和行为,各个品种相同的代码则全都留在了 Bird 中,它未来的子类也将得益于这些共用的行为。

在前面的“演出预订”的例子中,我也可以采用同样的手法,创建一个委托超类。这样在 Booking 类中就不需要分发逻辑,直接调用委托对象即可,让继承关系来搞定分发。不过写到这儿,我要去吃晚饭了,就把这个练习留给读者吧。

从这两个例子看来,“对象组合优于类继承”这句话更确切的表述可能应该是“审慎地组合使用对象组合与类继承,优于单独使用其中任何一种”——不过这就不太上口了。

12.11 以委托取代超类(Replace Superclass with Delegate)

曾用名:以委托取代继承(Replace Inheritance with Delegation)

class List {...}
class Stack extends List {...}


class Stack {
  constructor() {
    this._storage = new List();
  }
}
class List {...}

动机

在面向对象程序中,通过继承来复用现有功能,是一种既强大又便捷的手段。我只要继承一个已有的类,覆写一些功能,再添加一些功能,就能达成目的。但继承也有可能造成困扰和混乱。

在对象技术发展早期,有一个经典的误用继承的例子:让栈(stack)继承列表(list)。这个想法的出发点是想复用列表类的数据存储和操作能力。虽说复用是一件好事,但这个继承关系有问题:列表类的所有操作都会出现在栈类的接口上,然而其中大部分操作对一个栈来说并不适用。更好的做法应该是把列表作为栈的字段,把必要的操作委派给列表就行了。

这就是一个用得上以委托取代超类手法的例子——如果超类的一些函数对子类并不适用,就说明我不应该通过继承来获得超类的功能。

除了“子类用得上超类的所有函数”之外,合理的继承关系还有一个重要特征:子类的所有实例都应该是超类的实例,通过超类的接口来使用子类的实例应该完全不出问题。假如我有一个车模(car model)类,其中有名称、引擎大小等属性,我可能想复用这些特性来表示真正的汽车(car),并在子类上添加 VIN 编号、制造日期等属性。然而汽车终归不是模型。这是一种常见而又经常不易察觉的建模错误,我称之为“类型与实例名不符实”(type-instance homonym)[mf-tih]。

在这两个例子中,有问题的继承招致了混乱和错误——如果把继承关系改为将部分职能委托给另一个对象,这些混乱和错误本是可以轻松避免的。使用委托关系能更清晰地表达“这是另一个东西,我只是需要用到其中携带的一些功能”这层意思。

即便在子类继承是合理的建模方式的情况下,如果子类与超类之间的耦合过强,超类的变化很容易破坏子类的功能,我还是会使用以委托取代超类。这样做的缺点就是,对于宿主类(也就是原来的子类)和委托类(也就是原来的超类)中原本一样的函数,现在我必须在宿主类中挨个编写转发函数。不过还好,这种转发函数虽然写起来乏味,但它们都非常简单,几乎不可能出错。

有些人在这个方向上走得更远,他们建议完全避免使用继承,但我不同意这种观点。如果符合继承关系的语义条件(超类的所有方法都适用于子类,子类的所有实例都是超类的实例),那么继承是一种简洁又高效的复用机制。如果情况发生变化,继承不再是最好的选择,我也可以比较容易地运用以委托取代超类。所以我的建议是,首先(尽量)使用继承,如果发现继承有问题,再使用以委托取代超类。

做法

在子类中新建一个字段,使其引用超类的一个对象,并将这个委托引用初始化为超类的新实例。

针对超类的每个函数,在子类中创建一个转发函数,将调用请求转发给委托引用。每转发一块完整逻辑,都要执行测试。

大多数时候,每转发一个函数就可以测试,但一对设值/取值必须同时转移,然后才能测试。

当所有超类函数都被转发函数覆写后,就可以去掉继承关系。

范例

我最近给一个古城里存放上古卷轴(scroll)的图书馆做了咨询。他们给卷轴的信息编制了一份目录(catalog),每份卷轴都有一个 ID 号,并记录了卷轴的标题(title)和一系列标签(tag)。

class CatalogItem...

constructor(id, title, tags) {
 this._id = id;
 this._title = title;
 this._tags = tags;
}

get id() {return this._id;}
get title() {return this._title;}
hasTag(arg) {return this._tags.includes(arg);}

这些古老的卷轴需要日常清扫,因此代表卷轴的 Scroll 类继承了代表目录项的 CatalogItem 类,并扩展出与“需要清扫”相关的数据。

class Scroll extends CatalogItem...

constructor(id, title, tags, dateLastCleaned) {
 super(id, title, tags);
 this._lastCleaned = dateLastCleaned;
}

needsCleaning(targetDate) {
 const threshold = this.hasTag("revered") ? 700 : 1500;
 return this.daysSinceLastCleaning(targetDate) > threshold ;
}
daysSinceLastCleaning(targetDate) {
 return this._lastCleaned.until(targetDate, ChronoUnit.DAYS);
}

这就是一个常见的建模错误。真实存在的卷轴和只存在于纸面上的目录项,是完全不同的两种东西。比如说,关于“如何治疗灰鳞病”的卷轴可能有好几卷,但在目录上却只记录一个条目。

这样的建模错误很多时候可以置之不理。像“标题”和“标签”这样的数据,我可以认为就是目录中数据的副本。如果这些数据从不发生改变,我完全可以接受这样的表现形式。但如果需要更新其中某处数据,我就必须非常小心,确保同一个目录项对应的所有数据副本都被正确地更新。

就算没有数据更新的问题,我还是希望改变这两个类之间的关系。把“目录项”作为“卷轴”的超类很可能会把未来的程序员搞迷糊,因此这是一个糟糕的模型。

我首先在 Scroll 类中创建一个属性,令其指向一个新建的 CatalogItem 实例。

class Scroll extends CatalogItem...

constructor(id, title, tags, dateLastCleaned) {
  super(id, title, tags);
  this._catalogItem = new CatalogItem(id, title, tags);
  this._lastCleaned = dateLastCleaned;
}

然后对于子类中用到所有属于超类的函数,我要逐一为它们创建转发函数。

class Scroll...

get id() {return this._catalogItem.id;}
get title() {return this._catalogItem.title;}
hasTag(aString) {return this._catalogItem.hasTag(aString);}

最后去除 Scroll 与 CatalogItem 之间的继承关系。

class Scroll extends CatalogItem{
  constructor(id, title, tags, dateLastCleaned) {
    super(id, title, tags);
    this._catalogItem = new CatalogItem(id, title, tags);
    this._lastCleaned = dateLastCleaned;
  }

基本的以委托取代超类重构到这里就完成了,不过在这个例子中,我还有一点收尾工作要做。

前面的重构把 CatalogItem 变成了 Scroll 的一个组件:每个 Scroll 对象包含一个独一无二的 CatalogItem 对象。在使用本重构的很多情况下,这样处理就够了。但在这个例子中,更好的建模方式应该是:关于灰鳞病的一个目录项,对应于图书馆中的 6 份卷轴,因为这 6 份卷轴都是同一个标题。这实际上是要运用将值对象改为引用对象(256)。

不过在使用将值对象改为引用对象(256)之前,还有一个问题需要先修好。在原来的继承结构中,Scroll 类使用了 CatalogItem 类的 id 字段来保存自己的 ID。但如果我把 CatalogItem 当作引用来处理,那么透过这个引用获得的 ID 就应该是目录项的 ID,而不是卷轴的 ID。也就是说,我需要在 Scroll 类上添加 id 字段,在创建 Scroll 对象时使用这个字段,而不是使用来自 CatalogItem 类的 id 字段。这一步既可以说是搬移,也可以说是拆分。

class Scroll...

constructor(id, title, tags, dateLastCleaned) {
  this._id = id;
  this._catalogItem = new CatalogItem(null, title, tags);
  this._lastCleaned = dateLastCleaned;
}

get id() {return this._id;}

用 null 作为 ID 值创建目录项,这种操作一般而言应该触发警报了,不过这只是我在重构过程中的临时状态,可以暂时忍受。等我重构完成,多个卷轴会指向一个共享的目录项,而后者也会有合适的 ID。

当前 Scroll 对象是从一个加载程序中加载的。

加载程序...

const scrolls = aDocument
  .map(record => new Scroll(record.id,
              record.catalogData.title,
              record.catalogData.tags,
              LocalDate.parse(record.lastCleaned)));

将值对象改为引用对象(256)的第一步是要找到或者创建一个仓库对象(repository)。我发现有一个仓库对象可以很容易地导入加载程序中,这个仓库对象负责提供 CatalogItem 对象,并用 ID 作为索引。我的下一项任务就是要想办法把这个 ID 值放进 Scroll 对象的构造函数。还好,输入数据中有这个值,不过之前一直被无视了,因为在使用继承的时候用不着。把这些信息都理清楚,我就可以运用改变函数声明(124),把整个目录对象以及目录项的 ID 都作为参数传给 Scroll 的构造函数。

加载程序...

const scrolls = aDocument
  .map(record => new Scroll(record.id,
              record.catalogData.title,
              record.catalogData.tags,
              LocalDate.parse(record.lastCleaned),
              record.catalogData.id,
              catalog));

class Scroll...

  constructor(id, title, tags, dateLastCleaned, catalogID, catalog) {
 this._id = id;
 this._catalogItem = new CatalogItem(null, title, tags);
 this._lastCleaned = dateLastCleaned;
}

然后修改 Scroll 的构造函数,用传入的 catalogID 来查找对应的 CatalogItem 对象,并引用这个对象(而不再新建 CatalogItem 对象)。

class Scroll...

constructor(id, title, tags, dateLastCleaned, catalogID, catalog) {
  this._id = id;
  this._catalogItem = catalog.get(catalogID);
  this._lastCleaned = dateLastCleaned;
}

Scroll 的构造函数已经不再需要传入 title 和 tags 这两个参数了,所以我用改变函数声明(124)把它们去掉。

加载程序...

const scrolls = aDocument
  .map(record => new Scroll(record.id,
              record.catalogData.title,
              record.catalogData.tags,
              LocalDate.parse(record.lastCleaned),
              record.catalogData.id,
              catalog));

class Scroll...

  constructor(id, title, tags, dateLastCleaned, catalogID, catalog) {
 this._id = id;
 this._catalogItem = catalog.get(catalogID);
 this._lastCleaned = dateLastCleaned;
}

results matching ""

    No results matching ""