4/24/07

“Protected” considered harmful (ok, not harmful… useless)


Currently I’m refactoring an old java code (ancient… almost prehistoric I must say). It was obvious that when they wrote it, java wasn’t mature enough and the techniques applied neither. As an example, it had a deep inheritance hierarchy (a classic OO beginner mistake… been there, done that ). I don’t want to bash the current code (or submit it to the daily WTF), because when I look at old code, I usually think: “hmm… that should be better if we did it this way…” (well, who doesn’t think his way is THE way ?), and now I have the opportunity to really do it, so I’m enjoying it.
The code also had a lot of protected methods intended to be invoked by subclasses. I remembered when I started learning OO (10 years ago? Darn, I feel a little old now…) that we should avoid protected.
Protected is like public but for some classes…
For fields, if you adhere to the philosophy that no field should be public, I think protected should be avoided for the same reasons that public should be avoided for fields (I should blog about it later). For methods, is a little more tricky, but if you think that the method could be used the object, why not make it public? If not, should be private. A special case maybe is when you want to provide special access to methods to modify the private structure but only in the context of a subclass.
After discussing it in comp.object, I came to the conclusion that with protected one can do nice implementation tricks, but it should be avoided because it asks for maintenance problems.
The only place I could think where protected doesn’t looks bad is for providing the callback points for a template method.
Well, maybe I have it all wrong, what do you think? :-D
Post a Comment