Techniquecore
Extract superclass
Make a new superclass for two classes that have features in common, and move the shared fields and methods into it.
- Family
- refactoring
- Intent
- Put what two classes share in one place.
Purpose
Two classes can grow the same features without a common parent: the same field, the same getter, the same calculation. The copies must then be kept the same by hand.
Extract superclass makes a new class above both, and moves the shared features into it. The catalogue card has Department, with totalAnnualCost, name and headCount, and Employee, with annualCost, name and id. After the refactoring, a new class Party has name and annualCost, and both classes extend it. Department keeps headCount, and Employee keeps id.1
Steps
- Make an empty superclass. Make both classes extend it.
- Test.
- Move the shared parts up one at a time: first the fields with Pull Up Field, then the constructor code with Pull Up Constructor Body, then the methods with Pull Up Method. Test after each move.
- Look at the methods that are left in the subclasses. If parts of them are the same, extract those parts and pull them up too.
- Look at the callers. Some of them can now use the superclass type.
Example
Before the refactoring, Department called its cost totalAnnualCost. The first step renames it to annualCost, so that the two classes have the same interface.
import assert from "node:assert/strict";
class Party {
constructor(name) { this._name = name; }
get name() { return this._name; }
}
class Employee extends Party {
constructor(name, id, monthlyCost) { super(name); this._id = id; this._monthlyCost = monthlyCost; }
get id() { return this._id; }
get annualCost() { return this._monthlyCost * 12; }
}
class Department extends Party {
constructor(name, staff) { super(name); this._staff = staff; }
get headCount() { return this._staff.length; }
get annualCost() { return this._staff.reduce((sum, e) => sum + e.annualCost, 0); }
}
const staff = [new Employee("Ana", "E1", 1000), new Employee("Bo", "E2", 1500)];
const parties = [...staff, new Department("Sales", staff)];
assert.ok(parties.every((p) => p instanceof Party));
console.log(parties.map((p) => `${p.name} ${p.annualCost}`));
[ 'Ana 12000', 'Bo 18000', 'Sales 30000' ]
A caller can now treat each party in the same way. The two annualCost getters stay in the subclasses because their bodies differ.
| Language | What the example shows |
|---|---|
| JavaScript | a new class Party above Employee and Department, as above |
| Python | the same change; Party is an abstract base class, so a party without annual_cost cannot be made |
| Go | not inheritance: a Party struct that both types embed, and an interface for the shared method |
from abc import ABC, abstractmethod
class Party(ABC):
def __init__(self, name: str) -> None:
self.name = name
@property
@abstractmethod
def annual_cost(self) -> int: ...
class Employee(Party):
def __init__(self, name: str, id: str, monthly_cost: int) -> None:
super().__init__(name)
self.id = id
self.monthly_cost = monthly_cost
@property
def annual_cost(self) -> int:
return self.monthly_cost * 12
class Department(Party):
def __init__(self, name: str, staff: list[Employee]) -> None:
super().__init__(name)
self.staff = staff
@property
def annual_cost(self) -> int:
return sum(e.annual_cost for e in self.staff)
try:
Party("nobody")
except TypeError:
print("Party is abstract")
staff = [Employee("Ana", "E1", 1000), Employee("Bo", "E2", 1500)]
print([f"{p.name} {p.annual_cost}" for p in [*staff, Department("Sales", staff)]])
Party is abstract
['Ana 12000', 'Bo 18000', 'Sales 30000']
package main
import "fmt"
// Party holds the shared field. Both types embed it.
type Party struct{ Name string }
// Coster is the shared method set.
type Coster interface{ AnnualCost() int }
type Employee struct {
Party
ID string
MonthlyCost int
}
func (e Employee) AnnualCost() int { return e.MonthlyCost * 12 }
type Department struct {
Party
Staff []Employee
}
func (d Department) AnnualCost() int {
total := 0
for _, e := range d.Staff {
total += e.AnnualCost()
}
return total
}
func main() {
staff := []Employee{{Party{"Ana"}, "E1", 1000}, {Party{"Bo"}, "E2", 1500}}
sales := Department{Party{"Sales"}, staff}
for _, c := range []Coster{staff[0], staff[1], sales} {
fmt.Println(c.AnnualCost())
}
fmt.Println(sales.Name)
}
12000
18000
30000
Sales
When to use
- Two classes with the same features. This is Duplicated code across classes.
- Callers that must treat both classes in the same way. A common superclass gives them one type.
Pitfalls
Delegation can be better. In Java, C# and JavaScript, a class can have only one superclass. If the shared part is not a part of what the classes are, move it into a separate class that both use. See Composition over inheritance. If the superclass later proves wrong, Replace Superclass with Delegate undoes it.
Shared names, different ideas. Two name fields can mean different things. Pull up only the features that mean the same thing in both classes.
Go and Rust. These languages have no class inheritance. In Go, put the shared fields in a struct that both types embed, and the shared method set in an interface. In Rust, use a trait for the shared methods and a struct field for the shared data.
Tools that do it
IntelliJ IDEA has Extract Superclass. Its documentation says: "The Extract Superclass refactoring lets you create a superclass for an existing class."4 Most IDEs for Java and C# have a similar action.
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
- Martin Fowler, Catalog of Refactorings, Extract Superclass, the entry, the Department, Employee and Party sketch
- Martin Fowler, Catalog of Refactorings, index, the entry extractSuperclass, its books and tags
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 12, Dealing with Inheritance, Extract Superclass
- JetBrains, IntelliJ IDEA documentation, Extract superclass, the first paragraph
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 30JVFJ Edit this page History Report an error Markdown