Junior — Middle
Explain what a value object is and how it is used in the design of software systems.
sobes.tech AI
Answer from AI
Value Object — is an object that is defined not by its identity but by the set of values of its properties. Unlike entities, value objects are considered equal if all their properties are equal.
In software system design, value objects are used to model concepts where data is important, not the uniqueness of the object. They typically:
- Do not have their own identifier.
- Are immutable.
- Are easily compared by value.
Example: a Money class with amount and currency fields. Two Money objects with the same values are considered equal.
class Money {
private float $amount;
private string $currency;
public function __construct(float $amount, string $currency) {
$this->amount = $amount;
$this->currency = $currency;
}
public function equals(Money $other): bool {
return $this->amount === $other->amount && $this->currency === $other->currency;
}
}
Using value objects helps make the code more expressive and reduces errors related to incorrect comparison or data modification.