Getters/Setters vs Public Fields
This cluster debates the use of getters and setters for private fields in languages like Java versus public fields or properties in other languages like C# and Python, questioning their value for encapsulation, boilerplate, and design.
Activity Over Time
Top Contributors
Keywords
Sample Comments
seems like a very convoluted and inefficient way to have getter and setters without saying those words
Curious question — why do people insist so much on fields being private and there being getters and setters, even when all that getters do is return the field and all that setters do is set it? What kind of problem does this arrangement solve? Why not just use public fields?
Sorry to ask, but as a noob who just picked up Java, how do other languages address this issue? What's wrong with getters and setters?
An article about why using setters and getters for member variables is frequently a bad choice.
Getters and setters are a mediocre design choice, not a limitation. Records have existed for years, too.
I probably have 1000s of plain getters and setters in my code, and I never typed ANY of them. lol. VSCode has a "Generate Getters and Setters" refactor function, and I can make them plain publics any time I want. So you can't blame the Java Language itself for their existence.
It’s become dogmatic in Java to automatically create getters and setters for every single private variable in the class - include mutable objects like Lists and Maps (so a reference from a getter can actually change the referenced object). I’ve pointed out more than once that these getters and setters - usually auto-generated by an IDE or an XML compiler - serve absolutely no purpose and you might as well just cut out the middle man and mark the variables public at that point. Nothing makes a J
Why do you need to write all these getters and setters? Why not just a public property?
Getters and Setters violate encapsulation just as much as accessing properties directly, so I don't bother with them unless I'm forced to. In languages like C++ they can make sense due to a need of allocating and freeing memory of things within the object, but it's still not OOP. What you have when you're using getters and setters is a fancy struct with methods, not an OO class. (There is a significant difference.) Stop pretending you're not using a struct and just access things directly or star
Instead of attributes that lead to creation of getters/setters, how about the simple notion of private or public access to members? I'm not sure which should be the default, but it sounds like Java programmers would like them private unless otherwise specified. Why add code when all you want is to restrict access?