One thing I've run into a few times is a service class (like a JBoss service) that has gotten overly large due to helper inner classes. I've yet to find a good way to break the class out. These helpers are usually threads. Here's an example:
/** Asset service keeps track of the metadata about assets that live on other
* systems. Complications include the fact the assets have a lifecycle and their
* physical representation lives on other systems that have to be polled to find
* out if the Asset is still there. */
public class AssetService
{
//...various private variables
//...various methods
public AssetService()
{
Job pollerJob = jobService.schedule( new AssetPoller() );
Job lifeCycleJob = jobService.schedule( AssetLifecycleMonitor() );
}
class AssetPoller
{
public void run()
{
// contact remote systems and update this service's private variables that
// track the assets.
}
}
class AssetLifecycleMonitor
{
public void run()
{
// look for assets that have meet criteria for a lifecycle shift
// and update this service's private variables as relevant.
}
}
}
So, what can happen if I have a couple helpers and they're at all complex, is the overall class file can get really large. I like the inner classes in that it makes clear the classes are wholly owned by the service and exist only to help that service. I've tried breaking the classes out and passing the parent service as a reference, which works mostly, but things I don't like are:
So, in short, breaking the classes out loses some of the encapsulation I like. But leaving them in can lead to some large java files. I've yet to find a good way to deal with this. C++ had the concept of "friends" which I've rarely missed, but would actually help in this case.
Thoughts?
On bytecode level inner classes are just plain Java classes. Since the Java bytecode verifier does not allow access to private members, it generates synthetic accessor methods for each private field which you use. Also, in order to link the inner class with its enclosing instance, the compiler adds synthetic pointer to the outer 'this'.
Considering this, the inner classes are just a layer of syntax sugar. They are convenient and you have listed some good points, so I'd list some negative aspects which you might want to consider:
P.S. I'm talking about non-trivial inner classes (especially ones that do not implement any interfaces). Three line listener implementations are good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With