10
In object orientation it is recommended to avoid the use of setters. The usual justification for this is that the logic that modifies the state of an object must be encapsulated in the object. Therefore, the ideal is the object to expose behaviors, and these behaviors have as a side effect their state modification.
The traditional example is a class representing a bank account. Instead of using a Setter to modify the balance, the balance is modified as a side effect of transactions such as transfers. It would be something like
public class ContaBancaria
{
public Saldo { get; private set; }
public bool Transfere(decimal valor, ContaBancaria conta)
{
// Logica de transferencia
}
}
It turns out that in some cases it is easy to identify state modification as a side effect of an object’s behavior. In the case of the account, the balance is modified when banking operations are carried out. In the case of a product that has its quantity controlled in stock, the quantity would be modified in buying and selling processes, etc.
The problem is that there are situations that it is really complicated to identify the state modification in this way.
Some examples: a class that models a client, a class that models a user, a class that models a company.
In general these classes are part of the domain. They are concepts of problem space, are terms of ubiquitous language, and are necessary for domain operations. More than that, in general these classes have several properties.
For example: a customer has a name, has a CPF, has an associated email address, has a phone, an address, etc.
And that confuses me. Because it is necessary to expose features to modify this state: change the name, the CPF, the email, the phone, the address, etc.
The problem is: what behavior is responsible for these changes? I think a lot and it doesn’t. When trying to give a name to the method that changes the name for example, I have no idea what it would be.
If I go this way, I’ll end up creating a method ModificaNome
, but this is totally equivalent to a Setter.
In these cases, where we cannot identify in principle a behavior responsible for changing the state of a set of properties, how we managed to avoid the use of setters and obtain a good object-oriented design?
The question starts from a wrong premise. You just don’t have to avoid using setters. Use setters whenever you need to.
– Caffé