I’ve seen some posts which has strong reason to avoid using protected:
Why have private fields, isn’t protected enough?
Why is Clean Code suggesting avoiding protected variables?
And there are some other posts suggested we don’t need inheritance actually:
Why should I prefer composition over inheritance?
And some other posts suggested that inheritance can have alternatives:
Is this a misuse of “composition over inheritance”?
Should I force “composition over inheritance” rule to class members?
So I have a rather ‘modern’ idea : If ‘protected’ field is so harmful, should OOP languages eliminate keyword ‘protected’ in order to force programmers to write clean and high quality codes? If the answer is ‘NO!’ , what is the reason to allow ‘protected’ fields? Eg: when do we need ‘protected’ actually?
6
It is all about avoiding noise and keeping your scope tight. The only way for descendants to access parent members would be to make those members publicly accessible, which would expose those members to clients (users of the class) as well. This could be not useful, puzzling and dangerous. It would most certainly not be clean. Littering would be the word, you would be littering internal functionality of classes all over your namespaces. It would be so messy.
2
Those advice is only against protected fields. You would still need protected
for methods. It is related to the common advice against public fields. In effect, they are arguing fields should always be private and only exposed through getters/setters.
It is sensible advice in general, but sometimes a public or protected field is the simplest and most straightforward approach, and adding getters/setters would be needless code bloat, so I would not like it enforced by the compiler. It all depends on context.
Inheritance suffers from numerous problems, such as the fragile base class problem, creating tight, bi-directional coupling and weakening encapsulation. Further it can make testing harder than it needs to be. (See Inheritance: just stop using it already! for details of all of the above [disclaimer: written by me]).
There are no use-cases that I have been able to find where inheritance works better than using a combination of designing to interfaces and using composition.
There therefore is a good case for having modern languages not support inheritance at all. However, if they do support it, then protected
remains needed. Without it, folk would still use inheritance, but they’d be forced to weaken their encapsulation even further by making those members that sub classes override, public
. And just removing inheritance from existing languages would break existing code, so that’s a non-starter too, unfortunately.
1