Today, while peacefully coding EJBs, I found myself writing code using the dreaded
PortableRemoteObject.narrow() again. Charles "Fischkopf" Miller went into some detail about how painful this is in one of his recent blog entries. But in case you haven't experienced the exquisite clunkiness of
PortableRemoteObject.narrow(), here is a code sample:
// Get a bunch of things Collection collection = home.findByInternalGroupingKey(internalGroupingKey); Iterator iter = collection.iterator(); // Take the first one PolicyOptionGroup policyOptionGroup = (PolicyOptionGroup) PortableRemoteObject.narrow( iter.next(), PolicyOptionGroup.class);
The call to
PortableRemoteObject.narrow() is required because the objects in the
collection returned by the finder do not actually implement PolicyOptionGroup interface. Which is surprising, if you think about it. If they did implement the PolicyOptionGroup interface, we could write the more idiomatic:
PolicyOptionGroup policyOptionGroup = (PolicyOptionGroup) iter.next();
(Which is quite long-winded enough in itself, but that is the subject of another blog entry.)
Based on the comments to Charles' blog entry by Thomas Roka-Aardal and Bob Lee, there is a good reason for this verbosity. It goes like this: EJBs use RMI, RMI is transported by IIOP - the CORBA protocol - and the existing CORBA libraries cannot possibly be wrapped or modified for the convenience of EJB programmers.
In other words, this ugliness is caused by exposing an implementation choice that is at least two steps removed from my EJB code. And the benefits? The only two offered are:
Surprisingly, Bob Lee - in his comment on Charles' blog arguing the case for
PortableRemoteObject.narrow() - pointed out that it was possible to hide the call to
PortableRemoteObject.narrow() from EJB client code. Excellent. Let's do it and knock out "2 lines" of code (plus method declarations) per finder per EJB client.