DEV Community

Discussion on: Avoid getters and setters whenever possible

Collapse
 
bobbypriambodo profile image
Bobby Priambodo • Edited

I think you're missing a bit of the point there.

Scott wasn't comparing which of the two (getters vs. public variable) is better. What he said is that getters and setters by default (e.g. when automatically generated by IDE, or shown in beginner examples) expose the variable just the same as making it public; however, people seem to appreciate getters more than public vars, even when they're essentially the same.

The point is reinforced in your last sentence that, above all, the problem is mutability.

Returning copies are not getters (or at least not what most think as getters); they're essentially behaviors. You have to do the extra work to make them only as exposed/encapsulated as necessary.

The point I took from this article is to always strive to make your variables private, and that means not even getters and setters, and only expose behaviors around that data. Which I think makes sense, with some caveats that also have been stated in this article. Not necessarily agreeing, but a good food for thought nonetheless.

Collapse
 
florianschaetz profile image
(((Florian Schätz)))

That's what I said... "the basic idea is not a bad one" - it was just surrounded by bad arguments for the wrong problems. By starting with the public member thing, the whole text got the wrong spin from the start and the following bad argument didn't help.

Directly addressing mutability, exposing behavior, adding methods that directly work on the members instead of just holding them in a dumb object, etc. is a great idea. But by surrounding it with discussions about public members vs. getters/setters, etc. just dilutes those great points.

Thread Thread
 
bobbypriambodo profile image
Bobby Priambodo

I see, and that I can agree with. Hopefully the readers can see beyond it too. Thank you for elaborating!