Sunday, February 12, 2006

Generics and the EJB Business Interface Pattern

A common EJB pattern which gets both praise and condemnation is the Business Interface Pattern. The very excellent Bitter EJB digs right in early on, pointing out one of the problems is that whereas remote interface methods must declare throws RemoteException, local interfaces are specifically forbidden from actually throwing this exception.

One idea I would like to try is to leverage generics:

 1 public class LocalException
 2         extends RuntimeException {
 3     // Constructors, et al
 4 }
 5 
 6 public interface SomeBusinessInterface<E extends Exception> {
 7     public void payForHoneymoon()
 8             throws E;
 9 }
10 
11 public interface LocalSomeBusinessInterface
12         extends SomeBusinessInterface<LocalException>, EJBLocalObject {
13     // Local methods
14 }
15 
16 public interface RemoteSomeBusinessInterface
17         extends SomeBusinessInterface<RemoteException>, EJBObject {
18     // Remote methods
19 }
20 

The generic specification for the exception hides RemoteException from the local interface, while it can harmlessly declare that the interface throws LocalException. Worth a try.

UPDATE: Fortunately, EJB 3.0 should moot all of this.

Also some variations include declaring a private constructor for LocalException so no one can actually create one to throw, and overriding the declaration of the business methods in LocalSomeBusinessInterface to have no throws clause for any of the methods. Code generation is good for this.

Post a Comment