Immutable Objects Will Improve Your Life

Immutable Objects Will Improve Your Life

Learning about immutable objects improved my PHP code thoroughly. I’ve listed some helpful resources below that really helped me grasp the concept of immutability and value objects.

As a quick example, if your code sometimes looks like this:

class Weather { protected $region; public function setRegion($region) { $this->region = $region; } private function getRegion() { if (! $this->region) { throw new RegionNotSetException; } } public function doSomething() { $region = $this->getRegion(); // ... } }

When it should be looking (more) like this:

class Weather { protected $region; public function __construct($region) { $this->region = $region; } public static function fromRegion($region) { return new self($region); } public function doSomething() { $region = $this->region; // ... } }

Then I urge you to read up on immutable objects. Below are some of the articles that I found most helpful.

The Fowler Money Pattern

Here’s a very well written article, using Money as an example of an object that should be immutable.

Difference Between Entities and Value Objects

Originally published at