rossriley / php-scalar-objects

Experimental API for PHP Scalar Objects
70 stars 6 forks source link

Immutability #8

Closed mnapoli closed 10 years ago

mnapoli commented 10 years ago

Value objects should be immutable.

So each method should return a new object, different from $this, and should not modify the current instance.

This is particularly true for Array, for example:

public function sort() {
    sort($this);
    return $this;
}

Should be:

public function sort() {
    $array = clone $this;
    $result = sort($array);

    if ($result === false) {
        throw new Exception(...);
    }

    return $array;
}
rossriley commented 10 years ago

Thanks, good suggestion. https://github.com/rossriley/php-scalar-objects/commit/a0e38d8126a8dab5399d915b34ea0d0e74ae7cee

I'll make a note to update the other methods too.