Sometimes I don't get why we go so far as to make every single field as private and then create protected or publich getters for them [closed]
I don't think I am a total noob in OOP, but do you sometimes feel we go a little too far in privatizing the fields? Do you have a good rule of thumb as to when a field absolutely must be private, and when is it (maybe) okay to mark it protected, or public?
Sometimes it's the obvious thing that gets me.
Discuss
The simple rule:
Interface should be public. Implementation should be private.
When you make a field public (or even protected), you are effectively declaring it as part of the interface. Problem is, it's an implementation detail -- in almost every case, that field means something to your code. Anyone that wants to set it can, but you have to carefully explain how it needs to be set in order to keep the whole thing from crashing and burning. You can't even validate it as it's being set, so you need to validate it every...single...time before you use it, which can kill performance depending on how the validation needs to be done. (Even then, there's no guarantee that the field will stay valid, because you can't even enforce synchronized access to it.) And everyone using your class will have to do the same thing, cause $DEITY only knows what other code has been mucking around with that field and possibly corrupting it.
On top of all that, once it's a field, people are going to write code that expects to use that field. And in the cases where you find you need any of that validation later, you can't just convert a field to a getter/setter without breaking binary compatibility (meaning anyone who used your code will have to recompile everything that used that field in order for it to work again). Do that too many times, and people will be afraid to use your API -- read: you won't have any users.
Getters and setters separate the implementation from the interface. They allow callers to get back something that is definitely valid, and let you make sure that anything going in is definitely valid. This makes things more predictable, more stable. So if you write code that will ever be used after you write it, non-trivial getters and setters (that validate the value, maybe synchronize, etc -- ie: do more than just blindly get and set a variable) are a good idea.
It's for the case when others are going to be using your code or classes. You can expose and control exactly what is to be interfaced with, and what is 'internal.'
If you're the only one who will ever use your code, then yes it is often going 'too far.'
I will get attacked for even suggesting this, but whatever...
精彩评论