Patterncore
Temporary Field
Also called optional field smell.
A code smell: an object has fields that hold a value only in some cases or during one computation, so a reader cannot tell when the field is valid and the code must check it each time.
- Family
- code-smell
- Intent
- Find the fields that are set only some of the time, give them a class of their own, and give the case where they are not set an object of its own too.
- Refactorings
- Extract class, Move function, Introduce special case
Intent
Find the fields of a class that hold a value only some of the time: only for some kinds of object, or only while one method runs. Move them into a class of their own, together with the code that uses them. If the code must also handle the case where the values are absent, give that case an object of its own, so that the callers stop checking.
Problem
A reader of a class expects each field to mean something for each object of the class. A temporary field breaks that rule. It is set for some objects and empty for others, or it is set at the start of one method and left behind when the method returns.
Refactoring describes the smell as a class with a field that is set only in certain circumstances, and notes that a reader can spend a long time working out why a field is there when it seems not to be used.1 The first edition adds a common cause: an algorithm that needs several values, where the programmer stores them in fields to avoid a long list of parameters, and the fields have a meaning only while the algorithm runs.2
The forces are these:
- The field is cheap to add. One more case needs one more value, and the class is already there.
- Each method that reads the field must know when it is valid. The checks for empty values spread across the class, and one forgotten check is a bug.
- A field set by one method for another method to read makes the order of calls part of the interface. A call in the wrong order reads a stale or an empty value.
- Several temporary fields that are set and cleared together are a group with no name, which is close to Data Clumps.
Solution
Refactoring gives the moves in order.1 The catalogue at refactoring.com has a card for each refactoring, and gives Introduce Null Object as another name for Introduce Special Case.3
- Give the fields a home: Extract Class. The fields that are valid together become the fields of one class, and that class always has them.
- Move the code with them: Move Function. The methods that read the fields move into the class.
- Name the empty case: Introduce Special Case. If the original class must work when the values are absent, give it an object of a second class with the same methods and the neutral behaviour. The checks for an empty field disappear.
For the fields that an algorithm uses while it runs, the first edition suggests the same Extract Class, so that the values and the algorithm live in an object that exists only for the run.2 Local variables and parameters are another fix, when the algorithm is small enough.
Wikipedia describes the special case object in the same terms. A null object "implements the expected interface but performs no action", which "avoids the need for conditional checks scattered throughout calling code".4
Example
An order has three promotion fields. They have a value only for orders with a promotion, and both methods of the order must check them first.
import assert from "node:assert/strict";
const sumCents = (items) => items.reduce((t, i) => t + i.cents * i.qty, 0);
// Before: the promotion fields are empty for most orders.
class OrderBefore {
constructor(items) {
this.items = items;
this.promoCode = null;
this.promoPercent = 0;
this.promoUntil = null;
}
applyPromo(code, percent, until) {
this.promoCode = code;
this.promoPercent = percent;
this.promoUntil = until;
}
total(day) {
const sum = sumCents(this.items);
if (this.promoCode !== null && day <= this.promoUntil) {
return sum - Math.round((sum * this.promoPercent) / 100);
}
return sum;
}
label() {
return this.promoCode === null ? "no promotion" : `promotion ${this.promoCode}`;
}
}
// After: the fields have a class, and the empty case has an object.
class Promotion {
constructor(code, percent, until) {
Object.assign(this, { code, percent, until });
}
apply(sum, day) {
return day <= this.until ? sum - Math.round((sum * this.percent) / 100) : sum;
}
get label() {
return `promotion ${this.code}`;
}
}
const noPromotion = { apply: (sum) => sum, label: "no promotion" };
class Order {
constructor(items, promotion = noPromotion) {
this.items = items;
this.promotion = promotion;
}
total(day) {
return this.promotion.apply(sumCents(this.items), day);
}
label() {
return this.promotion.label;
}
}
const items = [{ cents: 1250, qty: 2 }, { cents: 499, qty: 1 }];
const plainBefore = new OrderBefore(items);
const promoBefore = new OrderBefore(items);
promoBefore.applyPromo("SPRING", 10, "2026-04-30");
const plain = new Order(items);
const promo = new Order(items, new Promotion("SPRING", 10, "2026-04-30"));
for (const day of ["2026-04-01", "2026-05-01"]) {
assert.equal(plain.total(day), plainBefore.total(day));
assert.equal(promo.total(day), promoBefore.total(day));
}
assert.equal(promo.total("2026-04-01"), 2699);
assert.equal(promo.label(), promoBefore.label());
assert.equal(plain.label(), "no promotion");
console.log("promotion: tests pass");
promotion: tests pass
In the second version the order has no field that is empty for most orders. The rules for the date and the percentage are in Promotion, and the order calls the same two methods for each kind of order. The case with no promotion is one object, not a check in each method.
| Language | What the example shows |
|---|---|
| JavaScript | a promotion class and a special case object, as above |
| Python | the same split, with a dataclass and a special case object |
| Java | a Promotion interface with a record for the real case and a constant for the empty case |
| Go | a promotion interface with a struct for each case |
from dataclasses import dataclass
def sum_cents(items):
return sum(cents * qty for cents, qty in items)
# Before: the promotion fields are None for most orders.
class OrderBefore:
def __init__(self, items):
self.items = items
self.promo_code = None
self.promo_percent = 0
self.promo_until = None
def apply_promo(self, code, percent, until):
self.promo_code, self.promo_percent, self.promo_until = code, percent, until
def total(self, day):
s = sum_cents(self.items)
if self.promo_code is not None and day <= self.promo_until:
return s - round(s * self.promo_percent / 100)
return s
def label(self):
return "no promotion" if self.promo_code is None else f"promotion {self.promo_code}"
# After: the fields have a class, and the empty case has an object.
@dataclass(frozen=True)
class Promotion:
code: str
percent: int
until: str
def apply(self, s, day):
return s - round(s * self.percent / 100) if day <= self.until else s
@property
def label(self):
return f"promotion {self.code}"
class NoPromotion:
label = "no promotion"
def apply(self, s, day):
return s
NO_PROMOTION = NoPromotion()
class Order:
def __init__(self, items, promotion=NO_PROMOTION):
self.items = items
self.promotion = promotion
def total(self, day):
return self.promotion.apply(sum_cents(self.items), day)
def label(self):
return self.promotion.label
items = [(1250, 2), (499, 1)]
plain_before = OrderBefore(items)
promo_before = OrderBefore(items)
promo_before.apply_promo("SPRING", 10, "2026-04-30")
plain = Order(items)
promo = Order(items, Promotion("SPRING", 10, "2026-04-30"))
for day in ["2026-04-01", "2026-05-01"]:
assert plain.total(day) == plain_before.total(day)
assert promo.total(day) == promo_before.total(day)
assert promo.total("2026-04-01") == 2699
assert promo.label() == promo_before.label()
assert plain.label() == "no promotion"
print("promotion: tests pass")
promotion: tests pass
Promotionis a frozen dataclass, so its three fields are always set together and cannot change one at a time.NO_PROMOTIONis one shared object. It has the same two members asPromotion, soOrdercalls them with no check forNone.- Python's
roundrounds a half to the even number, while JavaScript'sMath.roundrounds a half up. The totals in this example have no halves, so the two agree.
import java.util.List;
public class Main {
record Item(int cents, int qty) {}
static int sumCents(List<Item> items) {
return items.stream().mapToInt(i -> i.cents() * i.qty()).sum();
}
// Before: the promotion fields are null for most orders.
static final class OrderBefore {
private final List<Item> items;
private String promoCode;
private int promoPercent;
private String promoUntil;
OrderBefore(List<Item> items) { this.items = items; }
void applyPromo(String code, int percent, String until) {
promoCode = code;
promoPercent = percent;
promoUntil = until;
}
int total(String day) {
int sum = sumCents(items);
if (promoCode != null && day.compareTo(promoUntil) <= 0) {
return sum - Math.round(sum * promoPercent / 100f);
}
return sum;
}
String label() { return promoCode == null ? "no promotion" : "promotion " + promoCode; }
}
// After: an interface with one record for the real case and one constant for the empty case.
sealed interface Promotion permits Discount, NoPromotion {
int apply(int sum, String day);
String label();
}
record Discount(String code, int percent, String until) implements Promotion {
public int apply(int sum, String day) {
return day.compareTo(until) <= 0 ? sum - Math.round(sum * percent / 100f) : sum;
}
public String label() { return "promotion " + code; }
}
enum NoPromotion implements Promotion {
INSTANCE;
public int apply(int sum, String day) { return sum; }
public String label() { return "no promotion"; }
}
record Order(List<Item> items, Promotion promotion) {
Order(List<Item> items) { this(items, NoPromotion.INSTANCE); }
int total(String day) { return promotion.apply(sumCents(items), day); }
String label() { return promotion.label(); }
}
static void check(boolean ok, String what) {
if (!ok) throw new AssertionError(what);
}
public static void main(String[] args) {
List<Item> items = List.of(new Item(1250, 2), new Item(499, 1));
OrderBefore plainBefore = new OrderBefore(items);
OrderBefore promoBefore = new OrderBefore(items);
promoBefore.applyPromo("SPRING", 10, "2026-04-30");
Order plain = new Order(items);
Order promo = new Order(items, new Discount("SPRING", 10, "2026-04-30"));
for (String day : List.of("2026-04-01", "2026-05-01")) {
check(plain.total(day) == plainBefore.total(day), "plain " + day);
check(promo.total(day) == promoBefore.total(day), "promo " + day);
}
check(promo.total("2026-04-01") == 2699, "discount");
check(promo.label().equals(promoBefore.label()), "label");
check(plain.label().equals("no promotion"), "empty label");
System.out.println("promotion: tests pass");
}
}
promotion: tests pass
- The
sealedinterface lists the two cases. Aswitchover aPromotioncan then cover both without a default branch. NoPromotionis an enum with one constant, which is a common Java form for a special case object that has no state.- The
Orderrecord has no field that can be null. Its second constructor supplies the empty case.
package main
import "fmt"
type item struct{ cents, qty int }
func sumCents(items []item) int {
t := 0
for _, i := range items {
t += i.cents * i.qty
}
return t
}
// Before: the promotion fields are zero values for most orders.
type orderBefore struct {
items []item
promoCode string
promoPercent int
promoUntil string
}
func (o *orderBefore) applyPromo(code string, percent int, until string) {
o.promoCode, o.promoPercent, o.promoUntil = code, percent, until
}
func (o *orderBefore) total(day string) int {
sum := sumCents(o.items)
if o.promoCode != "" && day <= o.promoUntil {
return sum - (sum*o.promoPercent+50)/100
}
return sum
}
func (o *orderBefore) label() string {
if o.promoCode == "" {
return "no promotion"
}
return "promotion " + o.promoCode
}
// After: an interface, with a type for each case.
type promotion interface {
apply(sum int, day string) int
label() string
}
type discount struct {
code string
percent int
until string
}
func (d discount) apply(sum int, day string) int {
if day <= d.until {
return sum - (sum*d.percent+50)/100
}
return sum
}
func (d discount) label() string { return "promotion " + d.code }
type noPromotion struct{}
func (noPromotion) apply(sum int, _ string) int { return sum }
func (noPromotion) label() string { return "no promotion" }
type order struct {
items []item
promotion promotion
}
func newOrder(items []item) order { return order{items, noPromotion{}} }
func (o order) total(day string) int { return o.promotion.apply(sumCents(o.items), day) }
func (o order) label() string { return o.promotion.label() }
func main() {
items := []item{{1250, 2}, {499, 1}}
plainBefore := &orderBefore{items: items}
promoBefore := &orderBefore{items: items}
promoBefore.applyPromo("SPRING", 10, "2026-04-30")
plain := newOrder(items)
promo := order{items, discount{"SPRING", 10, "2026-04-30"}}
for _, day := range []string{"2026-04-01", "2026-05-01"} {
if plain.total(day) != plainBefore.total(day) || promo.total(day) != promoBefore.total(day) {
panic("total " + day)
}
}
if promo.total("2026-04-01") != 2699 || promo.label() != promoBefore.label() || plain.label() != "no promotion" {
panic("discount or label")
}
fmt.Println("promotion: tests pass")
}
promotion: tests pass
- In Go the empty string and zero are the zero values, so the first version uses
promoCode != ""as its check. A real code that is empty would be read as no promotion, which is one more risk of the temporary field. noPromotionis an empty struct. It takes no memory, and each value of it is the same.newOrdersets the empty case, so thepromotionfield of an order made with it is never a nil interface.
Consequences
Each object has the fields that it uses. A reader of the order no longer needs to know when the promotion fields are valid, and a method cannot forget the check, because there is no check.
The class count goes up by one or two. For one field read in one place, a check may be clearer than a class. The fix earns its cost when several fields go together or when many methods check the same condition.
A special case object has a risk. Wikipedia warns that the pattern "can make errors/bugs appear as normal program execution".4 If an empty value is an error, a special case object hides it, and an exception or an option type is the better choice. Use a special case only for an absence that has a correct neutral behaviour, such as an order with no discount.
How to fix it
- Fields that are valid together for some objects: Extract Class, then Move Function for the code that reads them.1
- Checks for the empty case in many places: Introduce Special Case.1
- Fields used only while one algorithm runs: Extract Class for an object that holds the run, or local variables and parameters.2
Variants and related patterns
Data Clumps. Temporary fields that are set and cleared together are often a clump that needs a class. See Data Clumps.
Null references. A temporary field is usually null when it is not valid. See Null references.
Strategy pattern. The promotion and the empty case are two strategies for the same step. See Strategy pattern.
References
- Martin Fowler, with Kent Beck, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 3, Bad Smells in Code, Temporary Field
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 3, Bad Smells in Code, Temporary Field
- Martin Fowler, Catalog of Refactorings, the cards Extract Class, Move Function and Introduce Special Case (alias Introduce Null Object)
- Wikipedia, Null object pattern, revision 1378667334, the introduction, Description and Criticism
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 QFTPN4 Edit this page History Report an error Markdown