Question

I have some legacy code that looks pretty much like this:

public class RmiClient {

    public boolean method1() throws RmiException {
        try {
            IRmiServerMethods server = (IRmiServerMethods) Naming.lookup(serverName);
            return server.method1();
        }
        catch (NotBoundException e) {
            throw new RmiException("server not found");
        }
        catch (MalformedURLException | RemoteException e) {
            e.printStackTrace();
            throw new RmiException(e);
        }
    }

    public boolean method2(Parameter parameter) throws RmiException {
        try {
            IRmiServerMethods server = (IRmiServerMethods) Naming.lookup(serverName);
            return server.method2(parameter);
        }
        catch (NotBoundException e) {
            throw new RmiException("server not found");
        }
        catch (MalformedURLException | RemoteException e) {
            e.printStackTrace();
            throw new RmiException(e);
        }
    }
}

And the list of methods goes on for thousands of lines.

Is there a better way to deal with these excessive exception handling? How to get rid of this boiler plate? Is there some good programming pattern to handle this situation? Are aspects the way here?

While I'm sure that this question probably has been asked before, I cannot find it.

Was it helpful?

Solution

Is there a better way to deal with these excessive exception handling?

All the exceptions thrown by Naming.lookup() method are checked, thus you have to catch them or let that a method further up the call stack deal with them. There is not a workaround for this. However...

Is there some good programming pattern to handle this situation?

I think the problem is that your code is highly coupled with the fact that it needs to invoke RMI services. Add to your Client code an abstraction layer that hides the implementation details could be the solution.

A quite simple option is to use a helper class that have the responsability of execute the Naming.lookup() method and handle the thrown exceptions. Thus, every time the client code has to invoke a remote service, it will talk with this helper class which encapsulates the RMI invocation issues.

It hard to talk about patterns without to know the architecture of your application, but in general terms a pattern that aims decoupling will help you.

How to get rid of this boiler plate?

If you have thousand of lines of code with this problem, I don't see an easy way to get rid of this code. Probably the best option is to design a solution and to start using it with the new code and gradually refactor the existing one. I don't think that AOP can help you with this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top