Reputation: 59
What principle are we violating if we use a method to update an input object's fields?
An example:
class Data {
public int $someField = 0; // it's private with setSomeField method
public int $anotherField = 0;
}
class SomeUseCase
{
// ... some DI
public function updateData(Data $data): void
{
// ... some business logic
$data->someField += 5;
// ... anotherField wouldn't update here
}
}
$data = new Data();
$data->anotherField = 42;
$someUseCase = new SameUseCase();
$someUseCase->updateData($data);
I think, it's too hard to debug
Upvotes: -1
Views: 37
Reputation: 498
Using setters makes it more difficult to ensure the consistency of data according to business rules. Let's consider your example: $data->setSomeField($data->someField + 5);
. I can assume that the business requirement was to "increment the 'someField' of the entity by 5". With this requirement, using setters is a bad idea. Any user can write code like $data->setSomeField(10);
or even $data->setSomeField(-100);
, thereby violating the business requirement.
A better approach would be to create a method called $data->incrementFive()
, where the user has no choice but to call this method.
On the other hand, if the business rule is simply that the "someField" field must store any number, then there is no problem in creating a setter like $data->setSomeField()
.
To decide whether to create a setter or not, ask yourself what you should do when you encounter unpredictable data, how many checks you should perform afterwards, or if it's better to limit manipulations with the data.
Upvotes: 1