One of the first things I do when I subclass a class is to change a
bunch of private methods to protected
Some reasoning about private
vs. protected
methods:
private
methods prevent code reuse. A subclass cannot use the code in the private method and may have to implement it again - or re-implement the method(s) which originally depend on the private method &c.
On the other hand, any method which is not private
can be seen as an API provided by the class to "the outer world", in the sense that third-party subclasses are considered "outer world" too, as someone else suggested in his answer already.
Is that a bad thing? - I don't think so.
Of course, a (pseudo-)public API locks the original programmer up and hinders refactoring of those interfaces. But seen the other way around, why should a programmer not design his own "implementation details" in a way that's as clean and stable as his public API? Should he use private
so that he can be sloppy about structuring his "private" code? Thinking maybe that he could clean it up later, because no one will notice? - No.
The programmer should put a little thought into his "private" code too, to structure it in a way that allows or even promotes reuse of as much of it as possible in the first place. Then the non-private parts may not become as much of a burden in the future as some fear.
A lot of (framework) code I see adopts an inconsistent use of private
: protected
, non-final methods which barely do anything more than delegating to a private method is commonly found. protected
, non-final methods whose contract can only be fulfilled through direct access to private fields too.
These methods cannot logically be overridden/enhanced, although technically there's nothing there to make that (compiler-)obvious.
Want extendability and inheritance? Don't make your methods private
.
Don't want certain behavior of your class altered? Make your methods final
.
Really cannot have your method called outside of a certain, well-defined context? Make your method private
and/or think about how you can make the required well-defined context available for reuse through another protected
wrapper method.
That's why I advocate to use private
sparingly. And to not confuse private
with final
. - If a method's implementation is vital to the general contract of the class and thus is must not be replaced/overridden, make it final
!
For fields, private
is not really bad. As long as the field(s) can be reasonably "used" via appropriate methods (that's not getXX()
or setXX()
!).