Fixing Primitive Obsession with Value Objects
debt(d7/e7/b5/t5)
Closest to 'only careful code review or runtime testing' (d7). PHPStan and PHPMD listed in detection_hints can flag some duplicated validation patterns but cannot reliably detect primitive obsession itself — it takes code review to notice email/money/status strings scattered across the codebase.
Closest to 'cross-cutting refactor across the codebase' (e7). The quick_fix says 'start small' with one primitive, but truly fixing primitive obsession means introducing value objects and updating every call site, signature, and persistence layer that touched the primitive — cross-cutting across web/cli/queue contexts.
Closest to 'persistent productivity tax' (b5). Value objects become load-bearing types touched by many work streams (every Money/Email use), adding immutability and serialization concerns, but they don't define overall system shape.
Closest to 'notable trap most devs eventually learn' (t5). The misconception ('overkill for simple domains') plus common_mistakes (mutable setters, missing __toString, == equality, over-wrapping) are well-documented gotchas devs hit once and learn — not catastrophic, not trivial.
Also Known As
TL;DR
Explanation
Primitive obsession uses raw types where domain concepts belong: string $email, float $price, string $status. Problems: no validation enforced, no type safety distinguishing 'email string' from 'name string', business logic scattered across multiple callers. The fix: create small Value Object classes — Email, Money, OrderStatus — that validate and encapsulate the concept. Constructors throw on invalid input, so a valid VO instance is always well-formed. Methods can be added: $money->add($other), $email->domain(). PHP 8.1 readonly classes make VOs concise. PHPStan recognises distinct types, catching swapped-argument bugs statically. Start with the most-duplicated validation logic and extract outward.
Common Misconception
Why It Matters
Common Mistakes
- Value objects with setters — they should be immutable; create a new instance for changes.
- Not overriding __toString() for value objects used in string contexts — causes type errors.
- Value object equality checked with == instead of a dedicated equals() method or comparing properties.
- Wrapping every primitive — only wrap primitives that carry domain rules or validation; plain int IDs often do not need wrapping.
Code Examples
function charge(string $email, float $amount, string $currency): void {
// Which string is which? float can be negative?
}
function charge(Email $email, Money $amount): void {
// Email and Money enforce their own invariants
}