loading...
re: You brought a hot topic here my friend :) I start with the basics : OOP is useful, very OOP si very often wrongly used The mistake that can be ...
 

Actually, your second example isn't useless.

For sake of argument, your getter/setter is used in multiple locations throughout your application.

You've changed something/discovered a bug/etc. with that variable within your class when it's set to specific values. You can safely put in some input validation into your setter to only allow correct input values (you could even make it a boolean/return a success condition).

If you had direct access to the variable, not only would you have to create some sort of validation after the fact. You'd also have to change all references to the variable to now use your getters/setters.

This might be fine on smaller projects but in a large project or some sort of Framework/Library could cause lots of extra work.

In short, it's better to future proof in that case.

 

i got to disagree on the principes of future proof.
That is a conception key point :

  • or this variable needs validation and so it Requires Setter/Getter
  • or (as in the example I wrote) it doesn't need validation and so setter/getter are just one useless layer of abstraction.

The point you make that maybe in the future you'll need validation is very interesting: it confirms another OOP situations where developpers overlook properties roles and visibility.
But that is not an OOP requirement or practice it's a conception mistake that needs to be fixed.
My point is that many devs think setting private AND writing setter/getter is "the way to go" in all situations, that's wrong on many occasions.
Visibility/validation is an important part BUT of the conception phase.
I don't even mention security 'cause if it was not thought in conception something's wrong.

Code of Conduct Report abuse