DEV Community

Discussion on: PHP Typed Properties: Think Twice.

adrienh profile image
Adrien H • Edited

Doing anything else than getting a property in its getter, or setting it in its setter, breaks the Separation of Concerns. If validations are to be performed on the data of an instance, maybe you should prefer a real validation model; let's say, for the most simple example, a validate() method which would check each potential flaw in the values, like a wrong file name, a negative value in an age, etc. You would execute this validate() callback before the database inserts, for example.

That's exactly what OOP frameworks like Symfony are doing, and that's a good way to go. One should never introduce unpredictable behavior in a getter or a setter. Getter gets, setter sets. Separation of Concerns.

From this point, you could decide to simply stop using getters and setters. And let's admit that having a typed public property feels exactly the same that having a private properties with getters/setters, except with less code and slightly more perf'. You could find it hypocritical. After all, encapsulation is about hiding private implementations; a private property exposed by a public getter is not encapsulated.

I thought like that back then in Java, but I evolved and I use getters/setters today. That's a question of consistency:

First, the lack of native typed collections PHP is a problem and makes PHP type system still very incomplete (without even speaking of generics). Since we don't have types like string[], we still need adders on collections. Second, sometimes you would want to make a property read-only, and then you will need a getter with no setter. These specific needs can impose getters or adders in some cases, which leads to mixing pure public access with indirect method accessors. This mix feels kinda... I don't know... asymetric? Inconsistent. If there is only one case forcing me to use a getter or a setter, I will always use them, that's my way today.

To me, accessors are more about consistency than encapsulation.