After reading some answers my first point would be that in this context I do not believe should is the same as saying must which is not the same as saying have to, I think you are perhaps over emphasizing always.
- should implies there this is a generalized consensus that this is a better or more appropriate approach
- you should always declare your members private
- must implies that this is the way it is done
- you must always declare your members private
- have to implies no other option
- you have to always declare your members private
Indeed in all three examples (particularly given the circumstance from which this question derived) one would and IMO should (though neither must or have to) query any statement put to them, this is how you program the best computer of all. For example if someone was to say you should always do something despite the fact you know that this time doing so would be detrimental would you do it without questioning their rational?
I imagine in this case your tutor (quite probably for ease) has surmised to you, a better practice which indeed I (and perhaps many others) would agree with. The question I feel should never be why make a member private but in fact the inverse as to why make it public, taking as an example facebook, people clearly like to publicize information about themselves but, even then, maybe just my friends can see this, my family can see that, and you who I don't know can't see anything.
Bringing this back to OOP and in particular Java, one of the main reasons for getters and setters is IMO (and I may be wrong) a case of good semantic practice, you obj.getState()
and obj.setState()
as opposed to obj.state
and obj.state = 'foo'
, in both cases I would argue the process of doing so is imperative. I'd like to think object orientation is not solely about breaking away from this paradigm but among others encapsulating data and function into a reusable component. If we didn't hide anything do we just end up with some namespace for storing data and methods?
Another key point I believe boils down to overriding, classes inheriting from a super class containing public variables is now stuck with a public variable which to me sounds as though this could lead to a decrease in re-usability. By using getters and setters you have provided a way for sub-classes to override access to your variables, maybe add that bit of validation you never bothered with.
As for it being tedious regarding writing getters and setters this is really null and void as I think most IDE's will do much of this for you (and as I have just found lombok which looks pretty cool and reminds me of @property
etc in objective-c)
In short yes you should always use private members unless you have a good reason not to (DTO's would be, to some extent, a reasonable exception)