I came across this line in Effective C++:
Public means unencapsulated, and practically speaking, unencapsulated means unchangeable, especially
for classes that are widely used.Yet widely used classes are most in need of encapsulation, because
they are the ones that can most benefit from the ability to replace one implementation with a better
one
What does the author mean by “Public means unencapsulated, and practically speaking, unencapsulated means unchangeable”?
And how is unencapsulated unchangeable?
The general idea is simple. If you make something public, then someone can and probably will use it. Therefore, if you change something that is public, all of the code that uses it immediately breaks. Breaking people’s code is bad; it tends to lead to them not wanting to use your code anymore, since now you’ve forced them to rewrite all of their stuff just because you wanted to use a different type or something.
The public interface is a contract between the implementation of the class and the user of it. Changing that contract, particularly without advanced notice, is considered very rude.
If all of your code is internal, that’s fine. But if it’s not, if you’re making a library for others to use (whether locally or just selling a library), then people are less likely to be happy about interface changes.
It isn’t a matter of rules of C++; it’s simply a matter of rules of interface design. Since public things are part of the interface, you must be careful about what you make public.