Implementing a getter and setter on the same variable (effectively making it a public variable) might seem unnecessary, seeing as we have the public keyword, but simply making it public restricts how you can use it in the future.
Consider if, in the soon to become present, you have the need to run some code on the new value of a variable before it is set. If you had had the foresight to create a setter for it, this would be no problem. But if it is just a public variable, you can't do that without breaking every code that uses this variable.
As you have found out, a simple change to the class design can have a devastating effect on your entire application.
And moreover, if you intend to have some variables read-only and some public, having getters for some of them and direct calls to others will make your class horribly inconsistent. (I HATE inconsistencies :P)
In my mind it's either/or. Use getters/setters on everything or nothing.
(My preference being everything.)
Supposedly, the getters and setters reveal too much implementation detail because they are typed. What happens if the type changes in the future then everything that calls those getters and setters might have to be updated.
Would the code not have to be altered just as much if the type of a public member changed?
Not that this is an issue in PHP. It's a loosely-typed language so there is no need for typed methods/members.
Leave a comment: