DEV Community

Discussion on: Avoid getters and setters whenever possible

Collapse
 
arhanger profile image
Arhanger

Someone has never changed his code. Sorry, but afet this "In both classes, Car1.java and Car2.java, we get essentially the same result" i stopped reading. Public properties are not the same as getters and setters. With getters and setters we have an entry point to our business logic, with public properties we don't have any. After changing hundreds of calls to any property through the whole project you'll understand why. This is the first point.
The second point was mentioned in comments. Calls by reference. When you use public properties you usually don't bother with copying stuff. Why should I? Doing that hundred times. That leads to a couple of painfull bugs. The most common one are date objects being modified by reference. Hours thrown away trying to debug that one. Especially by middle/juniors.
Third, getters and setters can be covered with unit tests. If someone changes something you will see that.
The last and not least. It's a lot harder to control workflow with this approach. Instead of reviewing code design, you are forced to check every property call through the whole project. Not very effective.
It's not bad to try to find something new, but getters and setters are used not by chance. If you want to remove a tool, propose something to cover that gap. Good luck.

Collapse
 
mduran profile image
Miguel Duran

It shows that you stopped reading at that point. His point was not that public attributes are just as good or better than getters and setters, his point was that the internals of a class should be as restricted as possible and having getters and setters violates that.

If you actually read the article, you would see this:


```My "default" is to start with a private final member, set only by the constructor. No getter or setter!

If another class absolutely needs to see this member, I think about why. I try to see if there is a behavior that I can expose instead, and create a method for that behavior.```

Collapse
 
arhanger profile image
Arhanger

My points wasn't on good/bad. He said that both ways give you the same result. And this is wrong. That was what I wrote about.

Second, but not least. Getters and setters can also be restricted, if you need that.

Third, there could be dozens of parameteres. Constructor will become huge and I personally don't like that. For that I'd better use a factory, that will garantee to create a valid object. For any other call there's code review to deny them.

Fourth, there's metaprograming in many languages. That lets you use even private members. So I don't see a reason to be so paranoic about that. But private members could give you headache when writing unit tests or changing class with tens of references to that private member.

To conclude, my main point was that these two methods don't give you the same result. Hope that makes my thougts clearer.