If exists getters and setters, then should be used always even inside class. Of course if getter and setter do something more in method then it must be considered if it fullfils the needs.
Should be used not means must be used. Property can be used directly ( only inside class if property is private - and should be ) but in good practice is to use getter and setter.
So using property directly is possible, but I recommend use get
and set
because it give more flexibility and can do something more than tipical assign or get.
For example if in first place setter only sets something, but after a while setter is changed to do something more.
setName(name){
this.name=name;
}
So in code setName("John");
is equal name="John"
. But imagine that after a while we want to set another property when name
is set:
setName(name){
this.name=name;
this.nameIsSet=true;
}
another example ( Listener pattern ):
setName(name){
this.name=name;
this.listener.nameChanged(this.name); //we call listener that variable changed
}
Then programmer needs to find every assigment like name="John"
in class and refactor it to new behavior. If only setName
is used then no code change must be done.
Of course everything depends from need and is possible that setting, getting property from outside do something more and different and it not fullfils our need inside class.