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 costs 2-4 hours to diagnose because the null field looks valid from the class definition
- ●Lifecycle confusion: developers waste 30-60 minutes understanding when each field is valid during code review
- ●Test fragility: tests that depend on field population order break when the class is refactored
Estimated Annual Cost
Cost per instance by team size and codebase size. Based on $120,000 average developer salary. See full methodology.
| Team Size | Small (<50k LOC) | Medium (50k-200k) | Large (200k+) |
|---|---|---|---|
| 3 devs | $1,500 | $3,300 | $6,600 |
| 5 devs | $2,500 | $5,500 | $11,000 |
| 10 devs | $3,750 | $8,250 | $11,000 |
| 20 devs | $5,000 | $11,000 | $11,000 |
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