Patterncore
Incomplete Library Class
A code smell: a class from a library lacks a method that the program needs, the library cannot be changed, and the missing code is written again in each place that needs it.
- Family
- code-smell
- Intent
- Write the missing operation once, next to the library type, as a foreign function or a local extension, so that the clients call it in place of repeating it.
- Refactorings
- Introduce foreign method, Introduce local extension, Move function
Intent
When a type from a library lacks an operation that the program needs, and the library cannot be changed, write the operation once. Put it in a function that takes the library object as its first argument, or in a small type of the program's own that wraps or extends the library type. Then the clients call that one operation, and do not each repeat the code.
Problem
A library is written by people who cannot know every program that will use it. Sooner or later a program needs an operation that the library's class does not have: the next working day of a date, the median of a list, a case-insensitive key in a map. The usual fix for a missing method, moving it into the class, does not work, because the class is not the program's to change.
The first edition of Refactoring names this smell. It notes that the builders of libraries cannot foresee everything, that the library class usually cannot be modified, and that this makes the normal move of a method into the class impossible.1
The forces are these:
- The operation is short, so each client writes it inline. The copies drift, which is Duplicated Code.
- Each inline copy reads the library object's data more than its own, which is Feature Envy toward a class that cannot take the method.
- Some languages let a program add a method to a class it does not own. Wikipedia calls this a monkey patch when it is done at run time, and lists its pitfalls: a release of the patched software "may break the patch", and the patch "creates a discrepancy between the source code and actual behavior that can confuse developers".2
- A wrapper or a subclass of the library type is a type that other libraries do not know about. Each place where the program meets those libraries needs a conversion.
Solution
The first edition gives two refactorings, by the number of missing operations.1
- One or two operations: Introduce Foreign Method. Write a function in the client code that takes the library object as its first argument and does the missing work. The first edition suggests a comment that marks it as a method that belongs in the library class.
- Many operations: Introduce Local Extension. Make a class of the program's own, either a subclass of the library class or a wrapper around it, and put all the missing operations there.
Several languages give the foreign method a direct form. Wikipedia describes an extension method as "a method added to an object after the original object was compiled", and notes that "There is no syntactic difference between calling an extension method and calling a method declared in the type definition."3 The C# guide says that extension members let a program "add" methods "to existing types without creating a new derived type, recompiling, or otherwise modifying the original type".4 The Kotlin documentation adds the limit: extensions are resolved "statically, meaning the compiler determines which function to call based on the receiver type at compile time".5 An extension is a foreign method with a better syntax, not a change to the class.
Go does not allow a method on a type from another package. The specification says that the receiver base type "must be declared in the same package as the method".6 A Go program uses a function, or a defined type of its own whose underlying type is the library type.
Example
Three parts of a program each find the next working day after a date. The built-in Date has no such method, so each part has its own copy of the loop, and one of them forgets that Saturday is not a working day.
import assert from "node:assert/strict";
const day = (s) => new Date(`${s}T00:00:00Z`);
const iso = (d) => d.toISOString().slice(0, 10);
// Before: each client writes the missing operation inline.
function dueDateBefore(invoiceDate) {
const d = new Date(invoiceDate);
do d.setUTCDate(d.getUTCDate() + 1); while (d.getUTCDay() === 0 || d.getUTCDay() === 6);
return d;
}
function shipDateBefore(orderDate) {
const d = new Date(orderDate);
do d.setUTCDate(d.getUTCDate() + 1); while (d.getUTCDay() === 0); // forgot Saturday
return d;
}
// After: a foreign function, written once, that takes the library object first.
// It belongs on Date, which the program cannot change.
function nextWorkday(date) {
const d = new Date(date);
do d.setUTCDate(d.getUTCDate() + 1); while (d.getUTCDay() === 0 || d.getUTCDay() === 6);
return d;
}
const dueDate = (invoiceDate) => nextWorkday(invoiceDate);
const shipDate = (orderDate) => nextWorkday(orderDate);
for (const [from, to] of [["2026-11-13", "2026-11-16"], ["2026-11-14", "2026-11-16"], ["2026-11-17", "2026-11-18"]]) {
assert.equal(iso(dueDate(day(from))), to);
assert.equal(iso(dueDate(day(from))), iso(dueDateBefore(day(from))));
assert.equal(iso(shipDate(day(from))), to);
}
assert.equal(iso(shipDateBefore(day("2026-11-13"))), "2026-11-14"); // the inline copy ships on a Saturday
console.log("nextWorkday: tests pass");
nextWorkday: tests pass
In the second version the rule for working days is in one function, and the clients that need it call it. The function copies the date, so it does not change the caller's object, which the inline copies also had to remember.
| Language | What the example shows |
|---|---|
| JavaScript | a foreign function for Date, as above |
| Python | a foreign function for datetime.date, and a local extension as a subclass |
| Java | a foreign method in a utility class for LocalDate, and the TemporalAdjuster hook that the library offers |
| Go | a function for time.Time, and a defined type with methods as a local extension |
from datetime import date, timedelta
# Before: each client writes the missing operation inline.
def due_date_before(invoice_date):
d = invoice_date + timedelta(days=1)
while d.weekday() >= 5:
d += timedelta(days=1)
return d
def ship_date_before(order_date):
d = order_date + timedelta(days=1)
while d.weekday() == 6: # forgot Saturday
d += timedelta(days=1)
return d
# After, one or two operations: a foreign function that takes the library object first.
# It belongs on datetime.date, which the program cannot change.
def next_workday(day):
d = day + timedelta(days=1)
while d.weekday() >= 5:
d += timedelta(days=1)
return d
# After, many operations: a local extension as a subclass.
class Workday(date):
@classmethod
def of(cls, day):
return cls(day.year, day.month, day.day)
def is_workday(self):
return self.weekday() < 5
def next_workday(self):
return Workday.of(next_workday(self))
cases = [
(date(2026, 11, 13), date(2026, 11, 16)),
(date(2026, 11, 14), date(2026, 11, 16)),
(date(2026, 11, 17), date(2026, 11, 18)),
]
for start, want in cases:
assert next_workday(start) == want
assert next_workday(start) == due_date_before(start)
assert Workday.of(start).next_workday() == want
assert ship_date_before(date(2026, 11, 13)) == date(2026, 11, 14) # a Saturday
# The local extension is a date, so date code accepts it, but a date
# that other code makes is a plain date, and must be converted.
w = Workday.of(date(2026, 11, 13))
assert isinstance(w, date) and w.is_workday()
parsed = date.fromisoformat("2026-11-14")
assert not hasattr(parsed, "is_workday")
assert not Workday.of(parsed).is_workday()
print("next_workday: tests pass")
next_workday: tests pass
The subclass shows the cost of a local extension. A Workday is a date, so the library accepts it, but a date that the library or other code makes, such as the result of date.fromisoformat, is a plain date, and the program must convert it with Workday.of before it can call the extra methods.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjuster;
import java.util.List;
public class Main {
// Before: each client writes the missing operation inline.
static LocalDate dueDateBefore(LocalDate invoiceDate) {
LocalDate d = invoiceDate.plusDays(1);
while (d.getDayOfWeek() == DayOfWeek.SATURDAY || d.getDayOfWeek() == DayOfWeek.SUNDAY) {
d = d.plusDays(1);
}
return d;
}
static LocalDate shipDateBefore(LocalDate orderDate) {
LocalDate d = orderDate.plusDays(1);
while (d.getDayOfWeek() == DayOfWeek.SUNDAY) { // forgot Saturday
d = d.plusDays(1);
}
return d;
}
// After, a foreign method: a static method in a utility class, with the
// library object as its first parameter. It belongs on LocalDate, which is final.
static final class Dates {
private Dates() {}
static boolean isWeekend(LocalDate d) {
DayOfWeek w = d.getDayOfWeek();
return w == DayOfWeek.SATURDAY || w == DayOfWeek.SUNDAY;
}
static LocalDate nextWorkday(LocalDate d) {
LocalDate next = d.plusDays(1);
while (isWeekend(next)) {
next = next.plusDays(1);
}
return next;
}
// The library has a hook for this: a TemporalAdjuster, which LocalDate.with accepts.
static final TemporalAdjuster NEXT_WORKDAY = t -> nextWorkday(LocalDate.from(t));
}
public static void main(String[] args) {
List<LocalDate[]> cases = List.of(
new LocalDate[] {LocalDate.of(2026, 11, 13), LocalDate.of(2026, 11, 16)},
new LocalDate[] {LocalDate.of(2026, 11, 14), LocalDate.of(2026, 11, 16)},
new LocalDate[] {LocalDate.of(2026, 11, 17), LocalDate.of(2026, 11, 18)});
for (LocalDate[] c : cases) {
check(Dates.nextWorkday(c[0]).equals(c[1]), "nextWorkday " + c[0]);
check(Dates.nextWorkday(c[0]).equals(dueDateBefore(c[0])), "same as before " + c[0]);
check(c[0].with(Dates.NEXT_WORKDAY).equals(c[1]), "adjuster " + c[0]);
}
check(shipDateBefore(LocalDate.of(2026, 11, 13)).equals(LocalDate.of(2026, 11, 14)), "the copy ships on a Saturday");
System.out.println("nextWorkday: tests pass");
}
static void check(boolean ok, String what) {
if (!ok) {
throw new AssertionError(what);
}
}
}
nextWorkday: tests pass
LocalDate is a final class, so a local extension by subclass is not possible, and a wrapper would need a conversion at each call into java.time. The library gives a better place: LocalDate.with takes a TemporalAdjuster, an interface with one method, so the missing operation can be a value that the library itself knows how to apply. The class TemporalAdjusters holds the adjusters that come with the library, such as next(DayOfWeek).
package main
import (
"fmt"
"time"
)
func day(s string) time.Time {
t, err := time.Parse(time.DateOnly, s)
if err != nil {
panic(err)
}
return t
}
// Before: each client writes the missing operation inline.
func dueDateBefore(invoice time.Time) time.Time {
d := invoice.AddDate(0, 0, 1)
for d.Weekday() == time.Saturday || d.Weekday() == time.Sunday {
d = d.AddDate(0, 0, 1)
}
return d
}
func shipDateBefore(order time.Time) time.Time {
d := order.AddDate(0, 0, 1)
for d.Weekday() == time.Sunday { // forgot Saturday
d = d.AddDate(0, 0, 1)
}
return d
}
// After, one or two operations: a function that takes the library value first.
// Go does not allow a method on time.Time outside the package time.
func NextWorkday(t time.Time) time.Time {
d := t.AddDate(0, 0, 1)
for d.Weekday() == time.Saturday || d.Weekday() == time.Sunday {
d = d.AddDate(0, 0, 1)
}
return d
}
// After, many operations: a local extension as a struct that embeds time.Time.
// The methods of time.Time are promoted, and the added methods sit next to them.
type Workday struct{ time.Time }
func (w Workday) IsWorkday() bool {
return w.Weekday() != time.Saturday && w.Weekday() != time.Sunday
}
func (w Workday) Next() Workday { return Workday{NextWorkday(w.Time)} }
func main() {
cases := [][2]string{{"2026-11-13", "2026-11-16"}, {"2026-11-14", "2026-11-16"}, {"2026-11-17", "2026-11-18"}}
for _, c := range cases {
from, want := day(c[0]), day(c[1])
if !NextWorkday(from).Equal(want) || !NextWorkday(from).Equal(dueDateBefore(from)) {
panic("NextWorkday " + c[0])
}
if !(Workday{from}).Next().Equal(want) {
panic("Workday.Next " + c[0])
}
}
if !shipDateBefore(day("2026-11-13")).Equal(day("2026-11-14")) {
panic("the copy ships on a Saturday")
}
// A time.Time from the library must be wrapped before the extra methods
// can be called, and unwrapped with .Time where the library expects a time.Time.
w := Workday{day("2026-11-14")}
if w.IsWorkday() || w.Format(time.DateOnly) != "2026-11-14" || !w.Time.Equal(day("2026-11-14")) {
panic("Workday")
}
fmt.Println("NextWorkday: tests pass")
}
NextWorkday: tests pass
The struct that embeds time.Time is a local extension. The methods of time.Time, such as Format and Weekday, are promoted, so a Workday can call them. But a Workday is not a time.Time: a function that takes a time.Time needs w.Time, and a value from the library needs to be wrapped. A defined type such as type Day time.Time would be worse, because a defined type does not get the methods of its underlying type.
Consequences
The missing operation exists once, with a name, and it can be tested on its own. A reader sees nextWorkday(d) and knows what it does.
A foreign function is less visible than a method. A programmer who looks for the operation in the library's documentation will not find it, and may write another copy. Keep the foreign functions for a library type in one module, named after the type, so that a programmer can find them.
A local extension changes the type. A subclass or a wrapper must be created from the library object, and converted back when the program passes it to code that expects the library type. This is the cost of the adapter idea; see Adapter pattern. Before writing either one, check the library for a hook that was made for this purpose. Java's java.time has one, as the Java example shows.
How to fix it
- One or two missing operations: Introduce Foreign Method, or an extension method where the language has them.1
- Many missing operations: Introduce Local Extension, as a subclass or a wrapper.1
- Operations that the library would accept: propose them to the library's authors, and keep the foreign function until a release has them.
- A monkey patch: replace it with one of the above, unless the language community treats patches as the normal way to extend.2
Variants and related patterns
Adapter pattern. A local extension that wraps the library class is a kind of adapter. See Adapter pattern.
Duplicated Code. The copies of the missing operation are the cost of this smell. See Duplicated Code.
Feature Envy. A foreign method envies the library class by design, because it cannot live there. See Feature Envy.
References
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Incomplete Library Class; Chapter 7, Introduce Foreign Method and Introduce Local Extension
- Wikipedia, Monkey patch, revision 1374249116, the introduction and Pitfalls
- Wikipedia, Extension method, revision 1340525475, the introduction
- Microsoft Learn, Extension members (C# programming guide), the introduction
- Kotlin documentation, Extensions, the introduction and the section on static resolution
- The Go Programming Language Specification, Method declarations
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 SFDWDC Edit this page History Report an error Markdown