Wednesday, April 6, 2005

The price We've Paid

A few days ago I came across yet another example of why the implementation of parameterized types (sometimtes called "generics") in Java 5 (JDK 1.5) is going to hurt more than it helps. I dread the intricacy, complexity, and sinuosity that quickly results once you've started down this path...
Let me be clear, lest I get a flurry of emails from people who don't get my point: I am not arguing that parameterized types are without merit or use - of course every feature has a place where it will prove valuable. However, it is important to evaluate the cost of a feature when considering it. In the case of parameterized types in Java, the cost is an inordinate increase in syntax and complexitiy and mental overhead. The cost, IMNSHO, is very high - way too high to justify the feature.

Do we really want to have to write (or worse, read/maintain) this kind of code on a daily basis?
-------- Original Message --------
Subject: Re: (De)serialization and Type Safety?
Date: Fri, 25 Mar 2005 07:05:48 +0100
From: Philippe Marschall <xxxxxxx>
Organization: EclipseCorner
Newsgroups: eclipse.platform

What to do? Are these all ignorable warnings, given that I know I'm > putting a Map<String, List<String>> in at the other end? Even if so, I'd > still like to be able to write warning-free code Well it depends what you want, if you want type safety and get rid of the warning, something like this might work.
public Map<String, List<String>> readFromSteam(InputStream is)
throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(is);
Map<?, ?> currentLists = (Map<?, ?>) ois.readObject();
return this.copyToNewMap(currentLists);
}

private Map<String, List<String>> copyToNewMap(Map<?, ?> oldLists) {
Map<String, List<String>> newLists = new HashMap<String,
List<String>>();
for (Entry<?, ?> each : oldLists.entrySet()) {
String key = (String) each.getKey();
List<?> oldList = (List<?>) each.getValue();
List<String> value = this.copyToNewList(oldList);
newLists.put(key, value);
}
return newLists;
}

private List<String> copyToNewList(List<?> oldList) {
List<String> newList = new LinkedList<String>();
for (Object each : oldList) {
newList.add((String) each);
}
return newList;
}