[jdom-interest] JDom and Java5

Mattias Jiderhamn mj-lists at expertsystems.se
Tue Feb 26 10:11:02 PST 2008


Rolf Lear wrote (2008-02-26 16:16):
> ... the @suppress would remove the warning like you said. Unfortunately, I don't believe that is enough for an API.
>   
(Would you care to explain why compiler warnings must be avoided at all 
costs?)

> The API is like a contract, and, in the context given, it would really be wrong for there to be class-cast exceptions when the user retrieves a List<Element> but gets a ClassCastException when there happens to be an Attribute in there..... Once the data leaves the API the user should be able to trust that it is right.
In my opinion there are exceptions to this (and I don't mean 
ClassCastExceptions...). The root of the problem here is that the XPath 
expression itself is untyped in relation to Java. It's the same thing 
with SQL. If I do a "SELECT string_column FROM table_of_strings" and 
then try to getInt() on the ResultSet I get an exception, but I cannot 
blame this on the API.
There is a saying (at least in Sweden): "Shit in, shit out". If what you 
throw in is not correct, you cannot expect a correct output; or in this 
case, if your XPath does not match the types you expect to be returned, 
the API can't be held responsible.
And it does not matter if we add an expected return type parameter or 
create separate selectElements() methods - there WILL be a runtime error.

> Is there a way to validate the content of the list prior to returning it?
Sure, we could loop the results and check the class. But that will have 
a potentially large impact on performance. APIs should aim to optimize 
performance and any non-required performance drains (inside or outside 
the API code) should be optional. So I think it should be up to the user 
if s/he wants to do this check the type of the List contents and act 
accordingly.

> Again, my only reluctance so far is that it brings the burden of type checking out of the API and to the user, and the spirit of Generics is that type checking should not be required (or at least reduced) because it is guaranteed by the compiler (through compile warnings or errors...).
>   
A raw List or List<?> may be used to indicate the fact that we cannot 
make any guarantees to what is returned. "Cast the return value if you 
dare!", so to speak.

 /Mattias


More information about the jdom-interest mailing list