DEV Community

Ghulam Mujtaba
Ghulam Mujtaba

Posted on

Value Objects and Mutability in OOP

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 new Age 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) {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

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:

  1. Easier to understand: Predictable behavior without unexpected changes.

  2. Safer: Multiple parts of our program can't modify each other's data.

  3. Simpler: No need to worry about changing existing data.

  4. 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)