Re: Hiding methods from a public API
Chris wrote On 08/07/07 15:08,:
We publish a library. Some of the methods in the public classes are
intended for consumption by our customers, but others are just for
internal use. Ok, fine, declare those methods protected.
Are you sure you understand what "protected" means?
It means "accessible from all of this package, and also
from any class in any package anywhere at all that just
happens to extend this one, no matter who wrote it."
A difficultly arises when we want to access one of these internal-use
methods from a class in another package. Example:
com.mydomain.foo.MyFoo wants to access a method in
com.mydomain.bar.MyBar
So the method has to be made public, which makes it available to our
customers. Not good.
Sounds like you've painted yourself into a corner.
Or maybe packaged yourself into a corner: Your division
of classes into packages does not reflect the ways those
classes relate to each other (if it did, you wouldn't have
this urge to make cross-package calls to package-private
methods). Arne Vajh=F8j's advice is good.
How do people generally handle this? I've been putting a "Do not use,
for internal use only" in the Javadoc for the method, but that's not id=
eal.
There are a couple of ugly hacks you might try, but
they are hacks and they are ugly:
- Deprecate all the "hands-off" methods. This won't
absolutely prevent their use, but may discourage it.
- Give each method an extra "enabler" argument whose
value is a class the customer cannot instantiate.
The way *you* get hold of an instance is to use a
static factory method that checks the identity of
its caller and throws if called from outside your
own suite of packages. (The consensus of another
current thread about this technique is that it is
a Bad Idea.)
--
Eric.Sosman@sun.com