DEV Community

Oliver Saywell
Oliver Saywell

Posted on

Who of you use getters & setters and when?

I've been developing commercially for coming up to a year now and work in a very small team of developers. The majority of what I have learnt with PHP I learnt myself but I have also learnt a lot in the last 6 months on an Open Uni course studying OOP with Java.

I wouldn't say I have come across much PHP material that specifically mentions the use of getters and setters, neither does the existing code base at the company I work for seem to use getters and setters. On the flip side while studying Java with the OU they seem to be pushing getters and setters religiously.

I am working on a new project and many of the classes I will be writing will be brand new classes introducing completely new functionality. So my question here is what is your experience with getters & setters and do you guys use them religiously regardless of language?

Thanks in advance for your input.

Top comments (3)

Collapse
 
wrongabouteverything profile image
wrong-about-everything

One of the areas where getters and setters are inevitable in I guess every project is ORM. While this is not mandatory at all. So either you use ORM and getters, or you use none of them.

Another area is UI, as Kasey Speakman mentioned. And this is not mandatory as well, check out this post.

But since almost every open source project requires my model to expose its data, I still have no choice most of the time.

Collapse
 
aleksikauppila profile image
Aleksi Kauppila • Edited

I think you should check out this great talk on good Doctrine practices by Marco Pivetta: youtube.com/watch?v=rzGeNYC3oz0. He talks about getting rid of getters and setters (among other things) by creating entities around their behaviour.

Collapse
 
kspeakman profile image
Kasey Speakman

Often getters and setters are a code smell called Inappropriate Intimacy in Object-oriented Programming. Another reference here.

Our legacy code makes extensive use of getters and setters, but that is really just procedural code operating on shared data. That's part of the reason it is considered legacy... because things are too tightly coupled and hard to change.

I sometimes will use objects with only getters and setters for "data buckets." These are temporary objects to hold raw data until I can validate it and convert it into a real object with behavior.

I often find that UI frameworks require the use of getters and setters for configuration / display purposes. This eventually leads me to create completely separate "data bucket" objects specifically for UI views.

Full disclosure: I don't use OOP paradigm much anymore. But I wish past me had considered getters and setters a code smell.