Programming Search⌘K

Techniquecore

Replace type code with subclasses

Also called extract subclass, replace type code with state/strategy.

Replace a field that holds a type code, such as "engineer" or "salesman", with one subclass for each value of the code.

Family
refactoring
Intent
Let the class of an object say what kind of thing it is.
Also called
Extract Subclass, Replace Type Code with State/Strategy

Purpose

A type code is a field whose value says which kind of thing an object is, for example the type of an employee. Code that depends on the kind tests the field with if or switch. When the same test is in many places, each new kind needs a change in each of them. See Repeated switches and Primitive obsession.

Replace type code with subclasses makes one subclass for each value. The behavior for each kind can then move into its subclass, with Replace Conditional with Polymorphism. The catalogue card changes createEmployee(name, type) from return new Employee(name, type); to a switch on the type that returns a new Engineer(name), a new Salesman(name) or a new Manager(name).1 The switch is now in one place, the factory function. The card names the inverse, Remove Subclass.1

Direct and indirect inheritance

  • Direct. The class with the type code gets the subclasses, as in the card. This works when the kind of an object never changes, and when the class has no other subclasses yet.
  • Indirect. The type code becomes an object of its own, such as EmployeeType, and that class gets the subclasses. The employee holds a type object. The type can then change at run time, and the employee class stays free for other subclasses. This form is the State or Strategy pattern, and the catalogue gives Replace Type Code with State/Strategy as an alias of the refactoring.1 See State and Strategy.

Steps

  1. Encapsulate the type code field, so that all code reads it through one getter.
  2. Pick one value of the code. Make a subclass for it, and override the getter of the type code to return the value.
  3. Make a factory function, or change the one that exists, to return the subclass for that value. See Replace Constructor with Factory Function.
  4. Test. Repeat steps 2 and 3 for each value.
  5. Remove the type code field from the superclass.
  6. Move the behavior that depends on the type into the subclasses with Replace Conditional with Polymorphism. Test after each move.

Example

Each employee had a type string, and the bonus was a switch on it. After the refactoring, the factory function has the only switch, and each subclass has its own bonus.

import assert from "node:assert/strict";

class EmployeeBefore {
  constructor(name, type) { this._name = name; this._type = type; }
  get bonus() {
    switch (this._type) {
      case "engineer": return 1000;
      case "salesman": return 3000;
      case "manager": return 5000;
      default: throw new Error(`unknown type ${this._type}`);
    }
  }
}

class Employee {
  constructor(name) { this._name = name; }
  get name() { return this._name; }
}
class Engineer extends Employee { get type() { return "engineer"; } get bonus() { return 1000; } }
class Salesman extends Employee { get type() { return "salesman"; } get bonus() { return 3000; } }
class Manager extends Employee { get type() { return "manager"; } get bonus() { return 5000; } }

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

for (const t of ["engineer", "salesman", "manager"]) {
  assert.equal(createEmployee("Ana", t).bonus, new EmployeeBefore("Ana", t).bonus);
}
const staff = [createEmployee("Ana", "salesman"), createEmployee("Bo", "manager")];
console.log(staff.map((e) => `${e.name} ${e.constructor.name} ${e.bonus}`));
Output
[ 'Ana Salesman 3000', 'Bo Manager 5000' ]

The bonus amounts are made up for the example.

Language What the example shows
JavaScript a type string replaced with three subclasses and a factory function, as above
Python the same change; the factory function looks up the class in a dictionary in place of a switch
Go not inheritance: each kind becomes its own type, and an interface Employee gives the shared methods
PythonGitHub
class Employee:
    bonus = 0

    def __init__(self, name: str) -> None:
        self.name = name


class Engineer(Employee):
    bonus = 1000


class Salesman(Employee):
    bonus = 3000


class Manager(Employee):
    bonus = 5000


CLASSES = {"engineer": Engineer, "salesman": Salesman, "manager": Manager}


def create_employee(name: str, type_code: str) -> Employee:
    return CLASSES[type_code](name)


staff = [create_employee("Ana", "salesman"), create_employee("Bo", "manager")]
print([f"{e.name} {type(e).__name__} {e.bonus}" for e in staff])
Output
['Ana Salesman 3000', 'Bo Manager 5000']
package main

import "fmt"

// Go has no subclasses. Each kind is its own type, and the interface gives the shared methods.
type Employee interface {
	Name() string
	Bonus() int
}

type base struct{ name string }

func (b base) Name() string { return b.name }

type Engineer struct{ base }
type Salesman struct{ base }
type Manager struct{ base }

func (Engineer) Bonus() int { return 1000 }
func (Salesman) Bonus() int { return 3000 }
func (Manager) Bonus() int  { return 5000 }

func createEmployee(name, typeCode string) (Employee, error) {
	switch typeCode {
	case "engineer":
		return Engineer{base{name}}, nil
	case "salesman":
		return Salesman{base{name}}, nil
	case "manager":
		return Manager{base{name}}, nil
	}
	return nil, fmt.Errorf("unknown type %q", typeCode)
}

func main() {
	for _, args := range [][2]string{{"Ana", "salesman"}, {"Bo", "manager"}} {
		e, err := createEmployee(args[0], args[1])
		if err != nil {
			panic(err)
		}
		fmt.Printf("%s %T %d\n", e.Name(), e, e.Bonus())
	}
}
Output
Ana main.Salesman 3000
Bo main.Manager 5000

When to use

  • The same test of a type code in many places. One subclass for each kind removes the tests.
  • Fields or methods that only some kinds use. They can move down into the subclass for those kinds. See Push Down Field.
  • A kind that changes at run time. Use the indirect form, with a type object.

Pitfalls

The kind changes. An object cannot change its class in most languages. If an employee can become a manager, direct subclasses do not work. Use the indirect form.

One axis only. A class can have one set of subclasses. If the objects vary in two ways, such as the type and the contract of an employee, use subclasses for one and delegates for the other. See Replace Subclass with Delegate.

Too little difference. If the subclasses only differ in a constant, a field is simpler. That is the inverse, Remove Subclass.

Go and Rust. These languages have no class inheritance. The Go form is one type for each kind and an interface for the shared methods. The Rust form is an enum with one variant for each kind and a match in each method, or one struct for each kind and a trait.

Tools that do it

No IDE has one action for the whole refactoring. The IDE can do some of the steps, such as the encapsulation of the field and the rename of the factory function.

The catalogue lists the refactoring in the first edition, the second edition and the Ruby edition, with the tag dealing-with-inheritance.2 In the second edition it is in Chapter 12, Dealing with Inheritance.3

References

  1. Martin Fowler, Catalog of Refactorings, Replace Type Code with Subclasses, the entry, the createEmployee sketch; inverse of Remove Subclass; aliases Replace Type Code with State/Strategy, Extract Subclass
  2. Martin Fowler, Catalog of Refactorings, index, the entry replaceTypeCodeWithSubclasses, its books and tags
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 12, Dealing with Inheritance, Replace Type Code with Subclasses

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/RCQY38/text.yaml