This post originated from an RSS feed registered with Java Buzz
by Norman Richards.
Original Post: Private methods are your friend
Feed Title: Orb [norman richards]
Feed URL: http://members.capmac.org/~orb/blog.cgi/tech/java?flav=rss
Feed Description: Monkey number 312,978,199
I would have never imagined that someone could be against the use
of private methods. I use private very liberally. Of course, all
instance variables are private. I never leave instance variables with
package or protected access. If I want my internal state to be
exposed, I'll expose it. The same is true of methods. Unless a method
is public API, I will normally make it private.
I don't normally design classes to be extended. I've been burned
by inheritence too many times to think that it's a good thing in
general. But occassionally I do. When I do, I try to design around
protected abstract methods. I won't go as far as to make the public
methods final, because that's a bit too presumptuous for me, but I
will make the internal methods private.
If you leave a method public, people will call it. It becomes
part of your public API whether you want it to or not. That type of
leakage is very bad. I don't want people relying on my
implementation. But if I don't want callers relying on my details, I
don't want to go protected and let subclasses have access either.
Inheritence is already fragile enough as it is. I don't want to add
to the problems with unnecesarily exposed methods. And the risk
increases when you allow subclasses to override your internal methods.
If any class has visibility enough into your implementation to feel
comfortable overriding code that wasn't meant to be overridden, they
probably have the ability to refactor the code to allow that to be
legitimate extension point.
So, private methods are your friends. They reduce the chance of
other classes coupling themselves to your internal functions and make
your code cleaner and more robust. That seems like a win to me.