Sobes.tech
Middle

What is an immutable object?

sobes.tech AI

Answer from AI

A immutable object is an object whose state cannot be changed after its creation. Any operation that appears to modify the object actually returns a new object with the changes.

Advantages:

  • Predictability: The object's state does not change unexpectedly.
  • Thread safety: No need to synchronize access to the object's state from different threads.
  • Simplified debugging: The object's state is known at any moment.
  • Caching: You can cache operation results, as they are always the same for a given object.

Example in PHP (although in standard PHP classes, immutability is not strict by default, it can be implemented):

<?php
final class ImmutablePoint
{
    private int $x;
    private int $y;

    public function __construct(int $x, int $y)
    {
        $this->x = $x;
        $this->y = $y;
    }

    public function getX(): int
    {
        return $this->x;
    }

    public function getY(): int
    {
        return $this->y;
    }

    // Method that "changes" the point but returns a new object
    public function move(int $dx, int $dy): self
    {
        return new self($this->x + $dx, $this->y + $dy);
    }
}

$point1 = new ImmutablePoint(1, 2);
$point2 = $point1->move(3, 4);

// The state of $point1 has not changed
// The state of $point2 is different
?>

In PHP, immutability is more common in libraries or when explicitly implemented in user-defined classes. Some built-in data types, such as strings and numbers, behave mainly as immutable.

What is an immutable object? — PHP - sobes.tech