stijn0713 Posted March 30, 2013 Share Posted March 30, 2013 Im studying modularity in PHP. Today i read about why defining properties (class variables) as public would be bad, and why it would be bad to read these variables directly without using getters and setters. I think this is bullshit, and has nothing to do with encapsulation. To my understanding, encapsulation enables changes without ripple effects. What i would like to hear is what (anticaped) changes could be made without ripple effects... Here is my thought: if you want to encapsulate a class member, this is because you want to change this variable independ of the calls to this variable, i.e. without needing to make change anywhere in the program. Suppose we are in a strong-typed language, and i have defined a class variable as an integer. If i would change this datatype to string, i will need to change the setter also and therefore the previous method calls to the setter won't work anymore and i will need to make N changes. Moreover, i would probably have assigned object variable to a variable of the type integer so here again i have to make N changes. Clearly combinatorial effects. The only thing you can do by defining getter and setters is to change the name of the class variable without combinatorial effects, on the condition that you don't change the getters and setters. But then again, why would i do this, i don't see a point in that. Please comment if you disagree Quote Link to comment https://forums.phpfreaks.com/topic/276319-encapsulation-public-properties/ Share on other sites More sharing options...
SurvivorZ Posted March 30, 2013 Share Posted March 30, 2013 It is, largely, bullshit. Consider: class Foo { private $bar; public function getBar() { return $this->bar; } public function setBar($bar) { $this->bar = $bar; } } is equivalent to class Foo { public $bar; } Encapsulation has to do with hiding the implementation details from the end-developer. Poorly encapsulated classes ask, then do. Well encapsulated classes don't ask, but get told what to do. Check out this Car class for an example of a very well encapsulated example. You see code like: $car = CarFactory::loadCar($_GET['car']); $car->turnOn(); $car->drive(60, 0.0); As a rule of thumb, well encapsulated code **rarely** needs to be queried to figure out what to do. It already has most logic paths already mapped out as public methods. Quote Link to comment https://forums.phpfreaks.com/topic/276319-encapsulation-public-properties/#findComment-1421946 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.