class Name
{
public function __construct(private string $firstName, private string $lastName)
{
if ($firstName === '' || $lastName === '') {
throw new InvalidArgumentException('The first and last name cannot be empty.');
}
}
public function firstName(): string
{
return $this->firstName;
}
public function lastName(): string
{
return $this->lastName;
}
public function formatted(): string
{
return $this->firstName . ' ' . $this->lastName;
}
}
Name
class is intentionally straightforward.
It consists of two properties, a constructor, and three methods.
The constructor is the sole injection point, ensuring that the object cannot be created without the necessary data.
It's a critical detail, especially for data validation.
If any data validation is required, it should be performed within the constructor.
Name
class also provides two simple getter methods for retrieving the first and last names.
These methods serve as straightforward accessors, without any additional logic.
Furthermore, the "formatted" method offers a convenient way to obtain the full name, a common requirement within the domain.
Immutability
The object must not change once created.Lack of Identity
It has no unique identity and is solely defined by its value.Defines Allowed Values
A Value Object defines the permissible range of values.Easy to Test
Value Objects are inherently testable due to their predictability.No-Brainer Usage
Incorporating Value Objects should be straightforward and intuitive in your codebase.