Sobes.tech
Junior — Middle

Does a class possess immutability if it has a public property?

sobes.tech AI

Answer from AI

If a class has a public property, it is not considered immutable because external objects can directly change the value of this property after the object is created.

Immutability means that the state of an object cannot be changed after its creation. To achieve this, all properties are usually made private or protected, and changes are only possible through methods that return a new object with the modified state.

Example of an immutable class in PHP:

class ImmutableUser {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function getName(): string {
        return $this->name;
    }

    public function withName(string $name): self {
        return new self($name);
    }
}

Here, the $name property is private, and it can only be changed by creating a new object through the withName method.

Does a class possess immutability if it has a public… - sobes.tech