The core ideaNo, it's not required: Bjarne Stroustrup, explained how he naively added protected
to C++ release 1.2, thinking to provide a useful feature to class developers, just to conclude only 5 years later that could justify the absenceit was a nasty source of bugs, that fortunately no one was forced to use. Nowadays, he recommends not to use it.
The practical arguments against protected
is proper encaspulationare the advantages of stronger encapsulation and the principle of the least knowledge:
- eitherEither a member is public
public
and can be used by anybody`anybody; - orOr the member is private
private
and needs to be protected against external access. And derived class written by another programmer are - A
protected
member, that requires careful usage (otherwise it would be public) can be misused as much subject to misuse private details as any other unrelatedby insiders (developers of derived class) as by anybody else.
In fact, protected members create a high risk of breaking the history ruleFormal arguments ofconfirm the practical experience. This has to do with the Liskov Substitution principle and more precisely its history rule:
We think it ought to be sufficient for a user to only know about the “apparent” type of the object; the subtype ought to preserve any properties that can be proved about the supertype.
- Barbara Liskov & Jeanette Wing in A behavioral notion of subtyping
Without going into formalthe details of the quoted article, the protected members allow a derived class (subtype) to change the state of the base class object (supertype) in an unexpected manner, without using one ofrelying on its public operations.
This being said, beware of the appearancesappearances and false promises. The Swift private
is in-between private
and protected
in other languages:
Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. (...).
- Apple, in The swift programming language