# Incomplete Library ClassLocalDate has no next business day, so five services copy the same loop and one forgets Sunday. Learn to centralise missing library behaviour with a Foreign Method or a Local Extension, and when to leave it.

A delivery app needs one small thing from its date class: the next business day. Skip Saturday, skip
Sunday, and give me Monday. Java's `LocalDate` has `plusDays` and `getDayOfWeek`, but no next
business day. So one developer writes the loop. Then another developer copies it. Soon the loop lives
in five services, and one copy forgets Sunday, so an order on Friday is promised for Sunday. That's a
smell called **Incomplete Library Class**: the library lacks something, and the missing piece gets
copied everywhere.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows
it section by section, with diagrams and a little extra depth.

{{< lesson-video youtube="WA16aPez3rM" title="Incomplete Library Class" >}}

## The missing method

Here is the app as a picture. The library has no `nextBusinessDay`, so every service carries its own
copy of the loop.

```mermaid {alt="Five services, Quote, Pickup, Invoice, Reminder and Refund, each hold their own copy of the next-business-day loop and each call LocalDate, which has no such method. The Invoice copy is wrong." caption="No method in the library, so five copies."}
flowchart LR
  Q["QuoteService<br/>own loop"] --> L["LocalDate<br/>no nextBusinessDay"]
  P["PickupService<br/>own loop"] --> L
  I["InvoiceService<br/>own loop (forgets Sunday)"] --> L
  R["ReminderService<br/>own loop"] --> L
  F["RefundService<br/>own loop"] --> L
  class Q,P,R,F c5
  class I bad
  class L c1
```

## The rented flat

Picture a rented flat. You'd love a shelf in the hallway, but the lease says no drilling into the
walls. You could try to change the wall, but it isn't yours. Or you could hang a hook wherever you
need one, a different hook each time.

The smarter move is a free-standing shelf. It stands next to the wall, holds everything, and leaves
the wall alone. The library class is the wall. It belongs to someone else, and it stays as it is. The
shelf is a class that you own. And when the landlord repaints the wall, which is a library upgrade,
your shelf still stands.

## What it looks like

Here are two of the five services. The quote service takes the order date, adds a day, and keeps
adding days while it lands on a weekend. The invoice service needs the same rule, so someone copies
the loop. But this copy checks only for Saturday.

```java
class QuoteService {
    LocalDate deliveryDate(LocalDate ordered) {
        LocalDate d = ordered.plusDays(1);
        while (d.getDayOfWeek() == DayOfWeek.SATURDAY
                || d.getDayOfWeek() == DayOfWeek.SUNDAY) {
            d = d.plusDays(1);
        }
        return d;
    }
}

class InvoiceService {
    LocalDate dueDate(LocalDate issued) {
        LocalDate d = issued.plusDays(1);
        while (d.getDayOfWeek() == DayOfWeek.SATURDAY) {
            d = d.plusDays(1);
        }
        return d;
    }
}
```

Honestly, the first developer did the sensible thing. The library had no such method, and there was
a deadline. Each copy is short, which is why nobody stops to ask where the rule should live.
Meanwhile, the rest of the app uses `LocalDate` happily. Only this one rule is missing.

## Why it hurts

Now it's Friday. A customer places an order. The quote service skips the weekend and says Monday.
The invoice service skips only Saturday, and says Sunday. Same question, two answers, and nothing in
the code explains why.

Then the business adds public holidays. Now you must find every copy, and edit each one the same
way. Copies drift apart, and a search for one won't find the others, because each was tweaked a
little. And every copy needs its own tests. The loop isn't the real problem. The real problem is that
the rule has no home.

## How to spot it

- **The same library call, followed by the same fix-up, in several places.** The Code Smells
  Reference gives this as the sign: calls to library functions whose results are modified the same
  way in several places.
- **Comments like "the library can't do this"**, or helper methods named after the library type,
  scattered across packages.
- **A loop that only exists to finish what the library started.** Here, the loop that keeps adding
  days.
- **A library that is read-only or out of date.** That's the usual cause: people patch around it, a
  few lines at a time.

One of these may be a coincidence. Several together mean a missing piece.

## Look first

Before you write anything, check whether the library already has it. Java's time package has
temporal adjusters, and one of them is called `next`.

```java
LocalDate monday = date.with(
        TemporalAdjusters.next(DayOfWeek.MONDAY));
```

`next` takes a day of the week and finds the first such day after your date. It's handy for the next
Monday, but none of the built-in adjusters skip weekends or know about business days. So the library
can't help here. It does let you plug in your own adjuster (`TemporalAdjusters.ofDateAdjuster`, used
with `with`), but the rule still has to live somewhere you own. Check the documentation, and newer
versions too. Someone may have added it already.

## The key insight: wrap it once

If a library class lacks something and you can't change it, put the missing behavior in one place that
you own. Like the shelf, it stands next to the wall. Callers use the shelf, and the wall stays as it
is. That gives the rule a name, a home, and one set of tests.

> **Can't change the library? Wrap it once, in one place.**

## The fix: Foreign Method

The first tool is a **Foreign Method**: one method that calls the library, adds the missing piece, and
returns the result. The course page uses that name. The refactoring.guru site calls it Introduce
Foreign Method. Here it's a static method in a small class called `BusinessDays`. It takes a
`LocalDate` and returns the next business day.

```java
final class BusinessDays {
    private BusinessDays() {}

    static LocalDate next(LocalDate date) {
        LocalDate d = date.plusDays(1);
        while (d.getDayOfWeek() == DayOfWeek.SATURDAY
                || d.getDayOfWeek() == DayOfWeek.SUNDAY) {
            d = d.plusDays(1);
        }
        return d;
    }
}
```

Every service now calls that one method. The copies are gone, and the Sunday bug disappears with them.

```java
class QuoteService {
    LocalDate deliveryDate(LocalDate ordered) {
        return BusinessDays.next(ordered);
    }
}

class InvoiceService {
    LocalDate dueDate(LocalDate issued) {
        return BusinessDays.next(issued);
    }
}
```

Fowler's original recipe puts a foreign method in the client class, with a comment that it belongs in
the library class. With five clients, one shared helper is the natural home (refactoring.guru makes
the same point: when several classes could use the method, a wrapper or shared home is better). This
simple rule ignores public holidays. If the rule grows, it grows in one place.

Fowler's second edition dropped both names from its online catalogue, so you'll mostly meet them on
the course page and in older books.

```mermaid {alt="Before and after the Foreign Method. Before, five services each contain their own loop and call LocalDate. After, the five services call BusinessDays.next, which holds the only loop and calls LocalDate." caption="Before and after."}
flowchart TB
  subgraph Before
    direction LR
    B1["5 services<br/>5 loops"] --> B2["LocalDate"]
  end
  subgraph After
    direction LR
    A1["5 services<br/>one call each"] --> A2["BusinessDays.next<br/>the only loop"] --> A3["LocalDate"]
  end
  Before ~~~ After
  class B1 bad
  class A2 good
```

## Introduce Local Extension

When you need several methods, not one, use **Introduce Local Extension**. Make a class of your own
that carries the new methods. The obvious way is a subclass. But `LocalDate` is final, so the
compiler refuses. (The Java documentation declares `public final class LocalDate`.)

```java
// error: cannot inherit from final LocalDate
class BusinessDate extends LocalDate {
}
```

So we wrap instead. A `BusinessDate` holds a `LocalDate` and adds the methods we want: `next`, and
`plusBusinessDays`.

```java
record BusinessDate(LocalDate date) {
    BusinessDate next() {
        return new BusinessDate(BusinessDays.next(date));
    }

    BusinessDate plusBusinessDays(int n) {
        BusinessDate result = this;
        for (int i = 0; i < n; i++) {
            result = result.next();
        }
        return result;
    }
}
```

Callers write: take this date, add three business days. The loop stays in one place, and the wrapper
delegates to the helper.

```java
LocalDate promised = new BusinessDate(ordered)
        .plusBusinessDays(3)
        .date();
```

The price of a wrapper is forwarding. Any `LocalDate` method you want on it, you must pass through
yourself. So wrap only when you need the extra methods. Name the wrapper after the idea in your
domain, like business date, not after the library.

```mermaid {alt="Class diagram of the fix. QuoteService and InvoiceService call BusinessDays. BusinessDate wraps a LocalDate and delegates to BusinessDays. BusinessDays reads LocalDate, which belongs to the library." caption="Your code stands next to the library class."}
classDiagram
  direction TB
  class QuoteService
  class InvoiceService
  class BusinessDate {
    next()
    plusBusinessDays(n)
  }
  class BusinessDays {
    next(LocalDate)
  }
  class LocalDate {
    plusDays()
    getDayOfWeek()
  }
  QuoteService ..> BusinessDays
  InvoiceService ..> BusinessDays
  BusinessDate ..> BusinessDays
  BusinessDate o--> LocalDate
  BusinessDays ..> LocalDate
```

## Related ideas

A wrapper looks like two patterns you may know. An [Adapter](/patterns/adapter-pattern/) wraps a
class to change its shape. Here, we add behavior instead. A
[Decorator](/patterns/decorator-pattern/) wraps a class to add behavior, but keeps the same
interface, so callers can't tell the difference. A `BusinessDate` is a new type, so it isn't one.

And the smell next door is [Duplicate Code](/code-smells/duplicate-code/). The five copies were duplicate code, and the missing method
is why they appeared.

## Myths, and when to leave it

**"If the library lacks a method, fork it, or patch it."** Patching third-party code works until the
next upgrade. Then you must re-apply your patch, and carry it forever. Wrapping or extending in your
own code leaves the library alone, so upgrades stay boring.

So when should you leave it?

- **When you need the behavior in exactly one place.** A private helper there is enough.
- **When the library's maintainers accept a contribution.** Sending the change upstream is the
  long-term fix, and your helper can go away.
- **When the extension costs more than it saves.** The course page and refactoring.guru both say to
  skip the refactoring in that case.

```mermaid {alt="Decision flow. Does the library already have it? If yes, use it. If no, is it needed in more than one place? If no, a local helper is fine. If yes, do maintainers accept a contribution? If yes, send it upstream. If no, one method means a Foreign Method, several methods mean a Local Extension wrapper." caption="When to wrap."}
flowchart TD
  Q1{"library already<br/>has it?"} -->|yes| U["use it"]
  Q1 -->|no| Q2{"needed in more<br/>than one place?"}
  Q2 -->|no| H["a local helper is fine"]
  Q2 -->|yes| Q3{"will maintainers<br/>accept it?"}
  Q3 -->|yes| UP["send it upstream"]
  Q3 -->|no| Q4{"one method<br/>or several?"}
  Q4 -->|one| FM["Foreign Method"]
  Q4 -->|several| LE["Local Extension<br/>(a wrapper if final)"]
  class FM,LE good
  class U,H,UP muted
```

## Recap

Incomplete Library Class means the library lacks something, and the missing piece gets copied
everywhere. Look for an existing method first. Then add the behavior in one place: a Foreign Method
for one helper, a Local Extension for several. Use a wrapper, because `LocalDate` is final. And skip
all this for a one-off, or send the change upstream.

```mermaid {alt="Recap chain: the library lacks it and copies spread, look first, then a Foreign Method or a Local Extension." caption="Wrap it once, in one place."}
flowchart LR
  A["library lacks it,<br/>copies spread"] --> B["look first"] --> C["Foreign Method or<br/>Local Extension"]
  class C good
```

Checklist:

- Is the same fix-up applied to a library result in more than one place?
- Does the library (or a newer version) already have the method?
- Do you need one method (Foreign Method) or several (Local Extension)?
- Is the library class final? Then wrap it instead of subclassing.
- Would the maintainers take a contribution?

> **Can't change the library? Wrap it once, in one place.**

## Further reading

- Code Smells Reference: [Incomplete Library Class](https://refactoring-assistant.github.io/couplers/incomplete-library-class).
- refactoring.guru: [Incomplete Library Class](https://refactoring.guru/smells/incomplete-library-class),
  [Introduce Foreign Method](https://refactoring.guru/introduce-foreign-method),
  [Introduce Local Extension](https://refactoring.guru/introduce-local-extension).
- Java SE 17 API: [LocalDate](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDate.html),
  [TemporalAdjusters](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/temporal/TemporalAdjusters.html).
- On this site: [Adapter](/patterns/adapter-pattern/), [Decorator](/patterns/decorator-pattern/).
