What is the basic difference of set
and get
in object-oriented programming?
What is the basic difference of set
and get
in object-oriented programming?
Assuming you want to know about a property or method of prefix set
and get
, this is used to encapsulate a state that must be internal to the object. They are used as facilitators in case of attributes that should be accessed simply and directly to get the value of an attribute ( get
) or change the value of this attribute ( set
) .
They are also called accessors and mutators .
In general it is said that they cause encapsulation illusion , because actually encapsulating is creating methods that do something special which does not encapsulate only access or assignment.
They are used to hide the details of how the state is stored and / or calculated, validated, etc.
There is a current that says they should always be used, even if you do not do any additional processing besides taking the value ( get
) or assigning the value ( ser
) to the class variable. So if one day you need to put something in it just changes the implementation of this pair of methods and everyone who consumes the object passes using the new form. This is an indirection . But there are those who are more pragmatic and only use when necessary, because in general it is easy to refactor.
Some languages have facilities for this pair of methods to look like a simple variable, this is the case for C # . It can be seen as different in Java .
They can be used separately. In fact, it is common to have get
and not set
. In some cases, set
is private or protected so only the object itself can access it.
See arguments to use in Java .
There's a explanation when using PHP .
See how it is used in Python .
Example in pseudocode:
class Cliente { //exemplo bem meia boa
private string nome; //note que é privado
public string getNome() => return nome; //aqui pega a variável interna e retorna
public void setNome(string nome) => this.nome = nome; //aqui joga o parâmetro na variável da classe
private decimal saldo;
public decimal getSaldo() => return saldo - 100; //dá uma margem de erro
public void setSaldo(decimal valor) => if (valor > 200) saldo = valor; //só aceita um mínimo de 200
}
The (GET)
method is used to retrieve a data and the (SET)
method is used to modify a given
In fact, there are many good reasons to consider using methods (getters and setters) instead of directly exposing fields in a class - in addition to the encapsulation argument and making future changes easier.
Here are some of the reasons: