Middle+
How are immutability and purity related?
sobes.tech AI
Answer from AI
Immutability (unchangeability of objects) and purity (functions with no side effects) are closely related, as immutability helps achieve purity.
A pure function:
- Always returns the same result for the same inputs.
- Does not modify the state outside its scope (has no side effects).
If a function takes mutable objects as arguments and modifies them, it is not pure, because its call can change the system state outside the function.
Using immutable objects:
- The function cannot change the objects passed to it, as they are immutable.
- Any "change" results in creating a new object, not modifying the existing one.
- This guarantees the absence of side effects related to changing the passed arguments.
Example:
<?php
// Mutable object
class MutablePoint {
public $x;
public $y;
public function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
}
// Impure function (modifies the passed object)
function moveMutablePoint(MutablePoint $point, $dx, $dy) {
$point->x += $dx;
$point->y += $dy;
}
$mutablePoint = new MutablePoint(0, 0);
moveMutablePoint($mutablePoint, 1, 1);
// $mutablePoint is now (1, 1) - state changed outside the function
// Immutable object
final class ImmutablePoint {
private $x;
private $y;
public function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
public function getX(): int {
return $this->x;
}
public function getY(): int {
return $this->y;
}
// Method returns a NEW object, not modifies the current one
public function move($dx, $dy): self {
return new self($this->x + $dx, $this->y + $dy);
}
}
// Pure function (works with immutable objects)
function moveImmutablePoint(ImmutablePoint $point, $dx, $dy): ImmutablePoint {
return $point->move($dx, $dy);
}
$immutablePoint = new ImmutablePoint(0, 0);
$newImmutablePoint = moveImmutablePoint($immutablePoint, 1, 1);
// $immutablePoint remains (0, 0) - state did not change outside the function
// $newImmutablePoint is now (1, 1) - a new object was created
Thus, using immutable objects is one way to create pure functions, which promotes more predictable, testable, and maintainable code.