This question about when to use private and when to use protected in classes got me to think. (I'll extend this question also to final classes and methods, since it is related. I'm programming in Java, but I think this is relevant to every OOP language)
A good rule of thumb is: make everything as private as possible.
- Make all classes final unless you need to subclass them right away.
- Make all methods final unless you need to subclass and override them right away.
- Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.
This is pretty straightforward and clear, but what if I'm mostly writing libraries (Open Source on GitHub) instead of applications?
I could name a lot of libraries and situations, where
- A library got extended in a way the developers would never have thought of
- This had to be done with "class loader magic" and other hacks because of visibility constraints
- Libraries got used in a way they were not built for and the needed functionality way "hacked" in
- Libraries couldn't be used because of a small issue (bug, missing functionality, "wrong" behavior) that could not be changed due to reduced visibility
- An issue that could not be fixed led to huge, ugly and buggy workarounds where overriding a simple function (that was private or final) could have helped
And I actually started naming these until the question got too long and I decided to remove them.
I like the idea of not having more code than needed, more visibility than needed, more abstraction than needed. And this might work when writing an application for the end user, where the code is only used by those who write it. But how does this hold up if the code is meant to be used by other developers, where it is improbable that the original developer thought of every possible use case in advance and changes/refactors are difficult/impossible to make?
Since big open source libraries are not a new thing, what is the most common way of handling visibility in such projects with object-oriented languages?