Techniquecore
Inline class
Also called merge class.
Move all the fields and methods of a class that does too little into the class that uses it, and delete the class; the inverse of Extract Class.
- Family
- refactoring
- Intent
- Remove a class that no longer pulls its weight by folding it into the class that uses it.
Purpose
A class costs something: a name to learn, a file to open, a step to follow from caller to code. It pays for itself when it holds a job. Sometimes it stops doing so. Other refactorings moved its work elsewhere, or it was made for a need that never came, and what is left is a field or two and a method that forwards a call.
Inline class moves what is left into the class that uses it, and deletes the class. The catalogue card is the reverse of Extract Class: a TelephoneNumber class whose area code and number fold back into Person.1 The inverse is Extract Class.
The book gives a second reason. When the split between two classes is in the wrong place, it can be easier to inline one into the other and then extract again along a better line, than to move features one by one between them.2 The first edition has the refactoring under the same name.3
Steps
- Run the tests and see them pass.
- In the target class, the one that will remain, write a method for each public method of the source class. Each one delegates to the source.2
- Change each caller of the source class to call the target's methods instead. Test after each.
- Move the fields and methods of the source into the target, one at a time, and test after each.
- When the source class has no callers and no content, delete it, and test.
Example
An order uses a Delivery class that holds only a tracking ID and builds one URL. After the refactoring, the order holds the ID and the method, and the class is gone.
import assert from "node:assert/strict";
// Before: a class that holds one field and one method.
class Delivery {
constructor(trackingId) { this.trackingId = trackingId; }
trackingUrl() { return `https://track.example/${encodeURIComponent(this.trackingId)}`; }
}
class OrderBefore {
constructor(id, trackingId) { this.id = id; this.delivery = new Delivery(trackingId); }
}
// After: the field and the method live in the order.
class Order {
constructor(id, trackingId) { this.id = id; this.trackingId = trackingId; }
trackingUrl() { return `https://track.example/${encodeURIComponent(this.trackingId)}`; }
}
for (const t of ["AB12", "x y/z"]) {
assert.equal(new Order(1, t).trackingUrl(), new OrderBefore(1, t).delivery.trackingUrl());
}
assert.equal(new Order(1, "x y/z").trackingUrl(), "https://track.example/x%20y%2Fz");
console.log("inline class: tests pass");
inline class: tests pass
Callers now write order.trackingUrl() and not order.delivery.trackingUrl(). If delivery later grows a carrier, a date and a status, the job is back, and Extract Class brings the class back.
| Language | What the example shows |
|---|---|
| JavaScript | a one-field class folded into its user, as above |
| Python | the same fold, with a delegating method kept for a time for the old callers |
| Go | the same fold, where an embedded struct is removed and its field moves up |
from dataclasses import dataclass
from urllib.parse import quote
# Step 2 of the mechanics: the target delegates to the source for a time.
class Delivery:
def __init__(self, tracking_id: str):
self.tracking_id = tracking_id
def tracking_url(self) -> str:
return "https://track.example/" + quote(self.tracking_id, safe="")
class OrderMidway:
def __init__(self, order_id: int, tracking_id: str):
self.order_id = order_id
self._delivery = Delivery(tracking_id)
def tracking_url(self) -> str:
return self._delivery.tracking_url()
# Steps 4 and 5: the field and the method move in, and Delivery is gone.
@dataclass
class Order:
order_id: int
tracking_id: str
def tracking_url(self) -> str:
return "https://track.example/" + quote(self.tracking_id, safe="")
for t in ["AB12", "x y/z"]:
assert Order(1, t).tracking_url() == OrderMidway(1, t).tracking_url()
assert Order(1, "x y/z").tracking_url() == "https://track.example/x%20y%2Fz"
print("inline class: tests pass")
inline class: tests pass
package main
import (
"fmt"
"net/url"
)
// Before: Order embeds a Delivery that holds one field.
type Delivery struct{ TrackingID string }
func (d Delivery) TrackingURL() string {
return "https://track.example/" + url.PathEscape(d.TrackingID)
}
type OrderBefore struct {
ID int
Delivery
}
// After: the field moves up into Order, and Delivery is deleted.
type Order struct {
ID int
TrackingID string
}
func (o Order) TrackingURL() string {
return "https://track.example/" + url.PathEscape(o.TrackingID)
}
func main() {
for _, t := range []string{"AB12", "x y/z"} {
before := OrderBefore{1, Delivery{t}}
after := Order{1, t}
if before.TrackingURL() != after.TrackingURL() {
panic(t)
}
}
if got := (Order{1, "x y/z"}).TrackingURL(); got != "https://track.example/x%20y%2Fz" {
panic(got)
}
fmt.Println("inline class: tests pass")
}
inline class: tests pass
When to use
- The class does too little. After other refactorings, a class with one field and a forwarding method is a Lazy Element, and the book names this refactoring as a fix for it.2
- The class was made for a future that did not come. That is Speculative Generality.
- Two classes are split in the wrong place. Inline one into the other, then extract along the right line.2
- A class only forwards. If most methods of the class pass calls to another object, see also Middle Man and Remove Middle Man.
Pitfalls
Other users of the class. If more than one class uses the source, inlining it into one of them leaves the others without it. Inline only a class that has one user, or move it to the user that owns it and leave the others to call that.
Polymorphism. A small class can be one of several implementations of an interface. Then its size is not the point: the interface is the job. Do not inline it.
A class at a boundary. A class that a framework, a serializer or another team depends on by name is part of an interface. Inlining it changes the interface.
Name clashes. Fields and methods from the source can have the same names as the target's. Rename before you move.
Tools that do it
IntelliJ IDEA's Inline action can "reverse the Extract refactoring for a method, constructor, parameter, superclass, anonymous class, and closure", and its Inline Superclass folds a superclass into its subclasses.4 For a class that is used as a field, as in the example, the steps above are done by hand or with the move actions of the tool, with a test after each.
References
- Martin Fowler, Catalog of Refactorings, Inline Class, the entry; inverse of Extract Class
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 7, Encapsulation, Inline Class, motivation and mechanics; Chapter 3, Bad Smells in Code, Lazy Element
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 7, Moving Features Between Objects, Inline Class
- IntelliJ IDEA documentation, Inline, the introduction; Inline Superclass
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 FE8ZPG Edit this page History Report an error Markdown