TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

Benefits of using value objects

The value object is a term crafted from Domain-Driven Design book. According to Wikipedia, a value object is a small object that represents a simple entity whose equality is not based on identity.

Money is a combination of a number and a currency. A period is a combination of a start time and end time. Both concepts are perfect candidates for value objects.

In this article, we share some benefits of using value objects.

Built-in validation

A value object is always valid since its existence. Which means, to guard its validity, we have to handle the validation from its constructor.

class Money
{
    private $number;
    private $currency;
 
    public function __construct($number, $currency)
    {
        if ($number < 0) {
            throw new LogicException('Invalid number for a money');
        }
 
        if (in_array($currency, $this->getCurrencyCode())) {
            throw new LogicException('Invalid currency for a money');
        }
 
        $this->number = $number;
        $this->currency = $currency;
    }
 
}

Safe usage

A value object is immutable, which means alter its attribute, it will return a brand new copy of itself. We never have to worry about changing a value object by reference.

class Money
{
    ... ...
 
    public function topUp(Money $money)
    {
        if ($money->getCurrency() != $this->getCurrency()) {
            throw new LogicException('Invalid topUp operation');
        }
 
        $newNumber = $money->getNumber() + $this->getNumber();
 
        return new Money($newNumber, $this->getCurrency());
    }
 
}

The end

The concept of value objects is very helpful. It can improve our object-oriented design a lot, so we can write easy-to-maintain codebase.