DEV Community

Discussion on: Avoid getters and setters whenever possible

Collapse
 
jstormes profile image
James Stormes

In PHP we also use reflection for hydrating objects. If all your objects properties have getters and setters you can hydrate by reflection, otherwise you have to write lots of exchange_array code.

However we can also hydrate on properties directly, but you don't get to do any validation of the data. As you say PHP is loosely typed, so that opens you up to hacking/injection.

What is harder to do is hydrate on both get/set and properties. So you wind up all ways using setters, even if you don't need them all the time.

Collapse
 
pocketstealer profile image
Pocketstealer

I think we are confusing bad practice with the role of getter/setter.

Bad practice is everywhere. But when you are using a getter/setter you expect to give a certain value and get a certain value.

You know you are setting a string. You will get a string. Thats the role of the getter/setter.
You are certain and sure that there will be in no circumstation a null there. Or a number. Always a string.

Using getter/setter for everything is bad as well. Leaving a variable there that is used and can be moddified to contain anything is even worse.

If you use get/set just to "return","$this->alfa = value" that's bad practice.

But a beginner doesn't know when should use it or not. So the one that's easiest to "implement after" it's the cheapest.

Scope of projects change. Agile is here and not always you have time to get all the information/specs or maybe some new information get there with constraints.

Always take the safest/easiest way rather than "smart way but it might blow up later".