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:

<?php

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:

<?php

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.

http://verraes.net/2011/04/fowler-money-pattern-in-php/

Difference Between Entities and Value Objects

Philip Brown wrote a very good explanation highlighting the differences between Entities (which are what your regular Laravel models are) and Value Objects. A real eye opener.

http://culttt.com/2014/04/30/difference-entities-value-objects/

An Interesting Discussion

Here’s a discussion debating the pros and cons of immutable objects, and a little history.

http://programmers.stackexchange.com/questions/151733/if-immutable-objects-are-good-why-do-people-keep-creating-mutable-objects

Immutability in Javascript

I’m been doing a lot of development in Vue.js recently, though I’ve never worked towards immutability in javascript. The article linked is an interesting read, and led me to discover immutability.js – a library created by Facebook with a number of immutable data structures.

http://www.sitepoint.com/immutability-javascript/

I wonder – does anyone have any experience in working with immutability in javascript with Vue.js or other similar frameworks? I’d be interested to hear your thoughts on the subject in the comments.

Leave a comment

Your email address will not be published.