Value Object
A Value Object represents a set of values and has three key characteristics:
Immutability: It's state cannot be changed once created.
Values: It holds a set of values (in this case, the age).
Equality criteria: It's equal by value (not by reference).
The Age
class is a Value Object because it represents a single value (age) and is immutable.
Immutability:
Immutability means an object's state cannot be changed after creation. The Age
class is immutable because:
The
age
property is private and only settable through the constructor.There are no setter methods to change the
age
property.The
increment
method returns a newAge
object with the incremented value, rather than modifying the existing object.
<?php
class Age {
private $age;
public function __construct($age) {
if ($age < 0 || $age > 120) {
throw new InvalidArgumentException('That doesn't make sense');
}
$this->age = $age;
}
public function increment() {
return new self($this->age + 1);
}
public function get() {
return $this->age;
}
}
$age = new Age(37);
$age = $age->increment();
var_dump($age->get()); // int(38)
function register(string $name, Age $age) {
// ...
}
In this example we don't have equality criteria but we can implement by using the 'equals' method.
Why use Value Objects and Immutability?
Using Value Objects and Immutability makes our code:
Easier to understand: Predictable behavior without unexpected changes.
Safer: Multiple parts of our program can't modify each other's data.
Simpler: No need to worry about changing existing data.
Reusable: Use the same data in multiple places without worrying about changes.
By using Value Objects and Immutability, we can make our code more reliable, easier to understand, and simpler to maintain.
Top comments (0)