# Temporary FieldA route planner whose fields are only filled while one method runs crashes when another method reads them early. Learn to spot a Temporary Field, give the job its own class, and know when a lazy cache is fine.

A parcel-tracking app has a class called `RoutePlanner`. It has three fields: `distances`,
`visited` and `bestSoFar`. They are only filled in while `planRoute()` runs. The rest of the time
they are null, or left over from the last trip. Then a report calls a second method before any
route was planned, and in production it throws a `NullPointerException`. That's a smell called
**Temporary Field**: a field that only matters for a moment.

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="QuMK7B4S3Ck" title="Temporary Field" >}}

## The scaffolding

Picture a building that has been finished for years, with scaffolding still standing against one
wall. It was needed for one job. While the work went on, it made sense. Once the job was done, it
stayed up, and nobody took it down. Now visitors walk around it and wonder what it holds up, and a
new builder who climbs it finds that it isn't safe.

The planner's fields are that scaffolding. They held up one job, planning a route, and they are
still standing in the class. A class's fields should describe the object all the time, not one
algorithm's scratch work.

## What it looks like

Here's the planner. It starts with three fields, and no constructor sets them. `planRoute` sets
them up fresh, then calls `search`, a private method that walks the graph and uses all three.
(`Graph` and `Edge` stand for a small graph type with `edgesFrom` and an edge with `to()` and
`km()`; the kilometres are made-up values.)

```java
class RoutePlanner {
    private Map<String, Integer> distances;
    private Set<String> visited;
    private Integer bestSoFar;

    int planRoute(Graph graph, String from, String to) {
        distances = new HashMap<>();
        visited = new HashSet<>();
        bestSoFar = null;
        search(graph, from, to, 0);
        return bestSoFar;
    }

    int lastBest() {
        return bestSoFar;
    }
```

And the private method it calls, still inside the same class:

```java
    private void search(Graph graph, String at, String to, int km) {
        int known = distances.getOrDefault(at, Integer.MAX_VALUE);
        if (visited.contains(at) || km >= known) {
            return;
        }
        distances.put(at, km);
        if (at.equals(to)) {
            bestSoFar = km;
            return;
        }
        visited.add(at);
        for (Edge e : graph.edgesFrom(at)) {
            search(graph, e.to(), to, km + e.km());
        }
        visited.remove(at);
    }
}
```

Honestly, that's a natural thing to write. `search` is recursive, and passing three extra values
through every call feels clumsy. The fields are right there. For a while, it works, as long as you
plan a route first and nobody else is using the planner.

## Why it hurts

**A hidden life cycle.** Before `planRoute`, the fields are null. During it, they are filled. After
it, they are stale.

**Reading too early.** Nothing stops a caller from reading before the first route. `lastBest`
returns an `Integer` field as an `int`, and unboxing a null throws:

```java
RoutePlanner planner = new RoutePlanner();
int km = planner.lastBest();
```

**Stale values lie.** Plan one trip, then ask about another, and you get the old answer for the
new trip.

**Two calls at once trample each other.** Both write to the same three fields.

**A new teammate can't tell.** Which of the fields are the planner, and which are scratch work?

The danger isn't the code you wrote. It's the order of calls you have to remember.

```mermaid {alt="Before and after. Before: planRoute and lastBest both use one RoutePlanner holding the fields distances, visited and bestSoFar, which are null before the call, filled during it and stale after it. After: planRoute makes a fresh RouteSearch for each call, and the fields live and die inside it." caption="Scratch fields move out of the long-lived object and into the job."}
flowchart LR
  subgraph after["After: a job object"]
    direction TB
    P2["RoutePlanner<br/>no fields"] -->|"new for each call"| S2["RouteSearch<br/>valid from construction"]
  end
  subgraph before["Before: scratch in the object"]
    direction TB
    P1["RoutePlanner<br/>distances, visited, bestSoFar"] --> N1["null before"]
    P1 --> F1["filled during"]
    P1 --> T1["stale after"]
  end
  class P1,N1,T1 bad
  class F1 hl
  class P2,S2 good
```

## How to spot it

1. **The constructor doesn't set it.** The field starts as null or a placeholder.
2. **One method sets it, then uses it**, right at the top.
3. **It is set only in some branches**, so it is unset when the other branch runs.
4. **Null checks guard it.** Each check says: this value might not be here.

Then search for every place that uses the field. If one method writes it and the others only read
it, that's scratch work. No single tell proves it alone; together, they are a strong sign. The
[course reference page](https://refactoring-assistant.github.io/object-oriented-abusers/temporary-field)
describes the same signs: fields not assigned in the constructor, fields used by one method that
sets them first, and fields assigned only in some branches.

## The key insight: fields describe the object all the time

Ask what a field is for. A field should describe the object itself, all the time. Scratch work
belongs to a job, not to the object, and when the job ends, the scratch work should end with it.

So ask each field: would this still be true if no job were running? If it wouldn't, it isn't the
object's field. It belongs to the job, so give the job its own home.

> **If it only matters during one job, it isn't the object's field.**

## The fix: Extract Class

The fix is **Extract Class**. Move the fields, and the methods that use them, into a new class
built for the job. Here it's the route search. The inputs come in through the constructor, and every
field is ready from the moment the object exists:

```java
class RouteSearch {
    private final Graph graph;
    private final String to;
    private final Map<String, Integer> distances = new HashMap<>();
    private final Set<String> visited = new HashSet<>();
    private int bestSoFar = Integer.MAX_VALUE;

    RouteSearch(Graph graph, String to) {
        this.graph = graph;
        this.to = to;
    }

    int run(String from) {
        search(from, 0);
        return bestSoFar;
    }
```

The `search` method moves over too. It no longer needs the graph and the target as parameters,
because they are fields now:

```java
    private void search(String at, int km) {
        int known = distances.getOrDefault(at, Integer.MAX_VALUE);
        if (visited.contains(at) || km >= known) {
            return;
        }
        distances.put(at, km);
        if (at.equals(to)) {
            bestSoFar = km;
            return;
        }
        visited.add(at);
        for (Edge e : graph.edgesFrom(at)) {
            search(e.to(), km + e.km());
        }
        visited.remove(at);
    }
}
```

The planner is left with one line. It makes a route search and runs it. No state, and no `lastBest`:

```java
class RoutePlanner {
    int planRoute(Graph graph, String from, String to) {
        return new RouteSearch(graph, to).run(from);
    }
}
```

Each call builds its own search, so two calls can't trample each other, and an old answer can't
leak into a new one.

This is a **method object**. Fowler's catalog calls the move **Replace Function with Command**; an
older name is **Replace Method with Method Object**. The course page says the same thing in its own
words: Extract Class for the fields and the code that uses them. Name the new class after the job,
not after the data. A route search says what it does.

```mermaid {alt="Class diagram of the refactored design. RoutePlanner has no fields and one method, planRoute. RouteSearch has a graph, a target, distances, visited and bestSoFar, all set at construction, and a run method. RoutePlanner creates a new RouteSearch for each call." caption="The job gets its own object; the planner keeps no scratch."}
classDiagram
  class RoutePlanner {
    +planRoute(Graph, String, String) int
  }
  class RouteSearch {
    -Graph graph
    -String to
    -Map distances
    -Set visited
    -int bestSoFar
    +run(String) int
  }
  RoutePlanner ..> RouteSearch : creates one per call
```

## Locals first, and a replay

Before you extract anything, ask a smaller question: does this need to be a field at all?

- If only one method uses it, make it a **local variable**.
- If two methods share it, pass it as a **parameter**.
- If several methods share the same scratch work, like `search` and its helpers, extract a class.
  That's when the job needs a home.

Now replay the failures. Reading too early? There is no `lastBest` to read. A stale answer? Each
search starts empty. Two calls at the same time? Each has its own fields. The call order stops
mattering.

## A second example: a parcel

Some fields wait for an event rather than a method. A parcel has two fields, `signedBy` and
`deliveredAt`. They only mean something after delivery:

```java
class Parcel {
    private String signedBy;
    private Instant deliveredAt;

    void deliver(String name, Instant when) {
        signedBy = name;
        deliveredAt = when;
    }

    String receipt() {
        if (signedBy == null) {
            return "Not delivered yet";
        }
        return "Signed by " + signedBy + " at " + deliveredAt;
    }
}
```

Until then, they are null, so `receipt` has to check, and every method that reads them needs the
same check.

Apply **Extract Class** again: a `Signed` record holds the name and the time, and always has both.
For the not-delivered case, add a **null object**, a proof that says "not delivered yet". Fowler's
newer name for this move is **Introduce Special Case** (Introduce Null Object is its alias):

```java
interface Proof {
    String describe();
}

record Signed(String signedBy, Instant at) implements Proof {
    public String describe() {
        return "Signed by " + signedBy + " at " + at;
    }
}

record NoProof() implements Proof {
    public String describe() {
        return "Not delivered yet";
    }
}
```

Now a parcel starts with the null object, `deliver` swaps in the real proof, and `receipt` just
asks. No null checks anywhere:

```java
class Parcel {
    private Proof proof = new NoProof();

    void deliver(String name, Instant when) {
        proof = new Signed(name, when);
    }

    String receipt() {
        return proof.describe();
    }
}
```

The course page's own examples follow the same two moves: a `PolynomialSolver` whose coefficient
fields were only needed for some equations was split into smaller solver classes (Extract Class), and
a `NullCustomer` replaced the null checks for a missing customer (Introduce Null Object).

## Where it comes from: Long Method and Large Class

Where does this smell come from? Usually a complex algorithm. It needs intermediate values, and
making them fields is the quick way to share them. (refactoring.guru adds that fields also dodge a
long parameter list.) A route search that began as one long method is the classic case, and
[Long Method](/code-smells/long-method/) is where the scratch values are born. Every scratch
field left behind then makes the class bigger and harder to read, which is one road to a
[Large Class](/code-smells/large-class/). Clean it up early.

## Myths, and when to leave it

**Myth: every field must always be set.** Not quite. A field can be optional, if the class owns that
fact. A **lazy cache** is fine: it starts empty, one method fills it, and nobody else touches it:

```java
private Rates rates;

Rates rates() {
    if (rates == null) {
        rates = loadRates();
    }
    return rates;
}
```

The smell is scratch state that leaks into the class's shape, where every method can see it and
trip over it.

So leave it alone when:

- it is an explicit, documented lazy cache behind a single method, or
- it is performance-critical code, where you've measured what a new object per call costs, and it
  matters.

Measure first, then decide. (The course reference page lists no cases to ignore; this list is our
own judgment.)

```mermaid {alt="Decision flow. Is the field set in the constructor and valid for the object's whole life? If yes, fine. If not, is it a lazy cache read through one method? If yes, leave it. If not, does one method use it? Make it a local. Do two methods share it? Pass it as a parameter. Do several methods share it? Extract a class. Is it a missing value that callers check for null? Use a null object." caption="When to refactor, and which tool to reach for."}
flowchart TD
  A{"valid for the object's<br/>whole life?"}
  A -->|yes| OK1["fine"]
  A -->|no| B{"a lazy cache behind<br/>one method?"}
  B -->|yes| OK2["leave it"]
  B -->|no| C{"how many methods<br/>use it?"}
  C -->|one| L["make it a local"]
  C -->|two| P["pass a parameter"]
  C -->|several| X["Extract Class"]
  C -->|"no value yet"| N["Null Object"]
  class X,N,L,P good
  class OK1,OK2 muted
```

## Recap

A temporary field is scratch work for one job, stored in an object that lives on. Spot it by
set-before-use and null checks. Fix it with a local, a parameter, Extract Class, or a null object.
It grows out of Long Method, and it feeds Large Class.

```mermaid {alt="Recap chain: scratch work in a field; spot it by set-before-use and null checks; fix it with a local, a parameter, Extract Class or a null object; related smells Long Method and Large Class." caption="If it only matters during one job, it isn't the object's field."}
flowchart LR
  A["scratch work<br/>in a field"] --> B["spot: set before<br/>use, null checks"] --> C["fix: local, Extract<br/>Class, Null Object"] --> D["related: Long Method,<br/>Large Class"]
  class C good
```

Checklist:

- Does the constructor leave the field unset?
- Does one method set it and then use it?
- Is it set only in some branches, or guarded by null checks?
- Could it be a local or a parameter instead?
- If several methods share it, does the job deserve its own class?

> **If it only matters during one job, it isn't the object's field.**

## Further reading

- [Temporary Field](https://refactoring-assistant.github.io/object-oriented-abusers/temporary-field), the course's Code Smells Reference.
- [Temporary Field](https://refactoring.guru/smells/temporary-field) on refactoring.guru.
- Fowler's refactoring catalog: [Replace Function with Command](https://refactoring.com/catalog/replaceFunctionWithCommand.html),
  [Introduce Special Case](https://refactoring.com/catalog/introduceSpecialCase.html).
