DEV Community

Cover image for Entities properties : public, protected or private ?
Xavier Dubois 🇫🇷
Xavier Dubois 🇫🇷

Posted on

Entities properties : public, protected or private ?

We all write a lot of models and entities, specially when we are working with frameworks like Symfony.

But, when you code them, you have to make a choice for the properties. Should they be public, protected or private ?

Symfony made a choice: private.
Laravel chose public.

My coworkers, inside our Symfony projects code them either protected or private, with a bunch of accessors.

I prefer the Laravel's way, and always code them with a public visibility.

I made that choice because most of the time (like 99% of the time), accessors are useless, they don't transform the data. I prefer access them with object->property instead of object->getProperty()

And you, what visibility is your default choice, and why ?

Top comments (4)

Collapse
 
sergey_telpuk profile image
Sergey Telpuk • Edited

An entity is a mutable object, so entity properties should be public, but if you want to guarantee that your entity must always have assigned particular property, make them private and require to pass via the constructor. See example,

Class Test
 private a

 Constructor(а){
  This->а = а;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
juyn profile image
Xavier Dubois 🇫🇷

Well, I do see the logic here, but if your concern is to guarantee that properties are set, using assertions and validators is easier and safer.
Constructors are good for tiny entities, but if they have more than 10 properties, good luck with that !

Collapse
 
sergey_telpuk profile image
Sergey Telpuk • Edited

No problem, do you know about value object? You always wrap up and pass it.
Please spend time on reading this book. After that, your doubts dissipate.

Collapse
 
anwar_nairi profile image
Anwar

I also like the Laravel way, it is even more fluid when accessing nested relationships.