Reputation: 621
For example, with a parent like this:
class Music {
private $timbre; // This?
protected $timbre; // Or this?
public function getTimbre(){
return $this->timbre;
}
}
In an inheriting child, is it OK from an OO point of view to access the member variable directly, or best to use the getters/setters?
class PostPunk extends Music {
public function doSomethingTimbreRelated(){
$punk_timbre = $this->getTimbre(); // This?
$punk_timbre = $this->timbre; // Or this?
// ... do something ...
}
}
I've read that keeping member variables private is better for encapsulation, but does that really matter in an inheritance hierarchy?
And I realize this is very trivial, but I sort of waffle back and forth to doing it both ways, so I'd like to settle in on one way
Upvotes: 0
Views: 79
Reputation: 621
After a bit of research, now I understand that using getters/setters promotes loose coupling to the parent object, via encapsulation.
In a small project with few developers and simple classes, the benefits of this are not obvious.
However, imagine a large project with many inheriting classes, as well as external classes consuming getters/setters.
If, down the road, you need to modify or add some business logic to the value returned by the getter, you will have to rewire all of the inheritors to use the getters VS accessing the properties directly.
Same goes for the setter - perhaps you decide to add some data sanitization/validation. Directly accessing the properties will bypass these future improvements.
Analogy: Rather than letting your kid have free access to your purse/wallet, you are forcing her to ask you for money, then you decide what and how much to give her.
Upvotes: 1