Wednesday May 02, 2007

Generic Advice

So you think you know everything there is to know about Java generics, eh? Well, we could use some advice. In the JXTA JSE 2.5 release we have added significant usage of generics to the existing JXTA APIs. In most cases the additional clarity is extremely beneficial and makes using and understanding the APIs simpler.

We have, however, run into at least one gnarly issue with generics in JXTA's Document APIs. Our original generics implementation for the Document APIs was built as suggested by the NetBeans and IDEA IDEs. It had some weaknesses though, especially in the messiness around using Enumerations over elements.

Illegal Enumeration Usage
public void method(XMLElement foo) {
   Enumeration<XMLElement> bar = foo.getChildren();

   while( bar.hasNextElement() ) {
      XMLElement baz = bar.nextElement();

      method(baz);
   }
}

The problem with this example is that foo.getChildren() returns Enumeration<? extends Element> and without casting that can't be assigned to the very pleasent Enumeration<XMLElement>. Casting, in addition to not being fun to type, is the evil we're trying to avoid by moving to use generics.

So, after reading a blog somewhere regarding some generics best practices I refactored the JXTA Document APIs a bit and came up with an alternative implementation. I've unfortunately lost the link to the original blog in the two months since I did the refactoring or I'd post it. I've also created an issue in the JXTA JSE Bugzilla, Issue #1655, to discuss the alternatives. The issue includes a patch to the current JXTA JSE CVS which presents my alternative second implementation.

If, after looking at both implementations, you have any advice (or better yet, a patch proposal) for improving the usage of generics in the JXTA JSE document APIs we would be very appreciative.

About

mduigou

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today