"Default approach" when creating a class from scratch: getters for everything, or limited access?
Posted
by
Prog
on Programmers
See other posts from Programmers
or by Prog
Published on 2014-05-29T23:29:15Z
Indexed on
2014/05/30
3:50 UTC
Read the original article
Hit count: 186
object-oriented
|encapsulation
Until recently I always had getters (and sometimes setters but not always) for all the fields in my class. It was my 'default': very automatic and I never doubted it. However recently some discussions on this site made me realize maybe it's not the best approach.
When you create a class, you often don't know exactly how it's going to be used in the future by other classes.
So in that sense, it's good to have getters and setter for all of the fields in the class. So other classes could use it in the future any way they want. Allowing this flexibility doesn't require you to over engineer anything, only to provide getters.
However some would say it's better to limit the access to a class, and only allow access to certain fields, while other fields stay completely private.
What is your 'default' approach when building a class from scratch? Do you make getters for all the fields? Or do you always choose selectively which fields to expose through a getter and which to keep completely private?
© Programmers or respective owner