Junior — Middle
How can you ensure the immutability of a class if it contains public properties?
sobes.tech AI
Answer from AI
To ensure the immutability of a class with public properties, you need to control access to these properties and prevent their modification after the object is created.
Main approaches:
- Make properties
readonly(if the language supports it) so they can only be set during initialization. - Use private properties with public getters and no setters.
- If properties are public and mutable, you can return copies of objects (for complex types) so external changes do not affect the internal state.
Example in PHP using constructor and getters:
class ImmutableClass {
public readonly string $name;
public readonly int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
}
If the PHP version does not support readonly, you can make properties private and add only getters:
class ImmutableClass {
private string $name;
private int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
public function getName(): string {
return $this->name;
}
public function getAge(): int {
return $this->age;
}
}
Thus, after creating the object, properties cannot be changed.