Temporary Field: What It Costs and How to Fix It
Instance fields that are only set and used in specific circumstances, remaining empty or null the rest of the time.
What It Is
A Temporary Field is an instance variable that only has a meaningful value under certain conditions. For the rest of the object's lifecycle, the field is null, zero, or an empty sentinel value. Developers reading the class must figure out when the field is valid and when it is not, creating an invisible invariant that the type system does not enforce. Temporary Fields often arise when a complex algorithm needs workspace variables, and the developer stores them as fields rather than passing them as parameters.
Why It Costs Money
Null pointer exceptions and undefined behaviour. Code that accesses a temporary field outside its valid context gets null or zero, leading to bugs that only manifest in specific execution paths.
The class interface is misleading. Fields suggest the object always has that data. Developers write code that reads the field without realising it may be empty, and the bug passes code review because the field looks legitimate.
Testing requires understanding the lifecycle. To test code that uses the temporary field, you must know exactly which methods populate it and in what order, increasing test complexity.
Specific Cost Mechanisms
- ●Null-access bugs: each incident is slow to diagnose because the null field looks valid from the class definition
- ●Lifecycle confusion: reviewers have to work out when each field is valid
- ●Test fragility: tests that depend on field population order break when the class is refactored
Estimated Annual Cost
Cost of one instance a year by team size, from our model at $180K fully-loaded cost per engineer. Low and high use the bottom and top of the Medium inputs; mid is halfway. See full methodology.
| Team Size | Low | Mid | High |
|---|---|---|---|
| 3 devs | $2K | $4K | $5K |
| 5 devs | $3K | $5K | $8K |
| 8 devs | $4K | $8K | $12K |
| 10 devs | $5K | $10K | $15K |
| 20 devs | $9K | $19K | $28K |
These are model outputs, not measurements. Every input is on the cost model page, and the same model produces the figures on the 22 smells page. Put in your own team and cost in the smell profile calculator.
How to Detect It
Specific rules and thresholds for automated detection. See full tool comparison.
Fields assigned in one method and read in another unrelated method
Null-check branches around temporary fields inflate complexity
Fields used in only one method path
Directly detects fields that should be locals or parameters
Refactoring Patterns
Proven techniques to eliminate this smell. See all refactoring patterns.
Extract Class
The temporary fields form a coherent group used by a specific algorithm
Replace Method with Method Object
A complex method uses temporary fields as workspace
Introduce Null Object
The temporary field has a meaningful null/empty behaviour