Saturday, January 28, 2006

Does Java 5 Generics give you better code?

I think I start to understand at least part of the Java 5 Generics now. I'm really not convinced that the benefit is worth the syntax and reduced readability. I'll try to explain why...

I must confess that I see the point for the simple cases. In Java 1.4 the code for finding payments over a certain limit in a list of Payments would look like this:


    public List findAllPaymentsOverLimit(List payments,
int limit)
{
List overLimitPayments = new ArrayList();
for(Iterator each = payments.iterator(); each.hasNext(); ) {
Payment payment = (Payment) each.next();
if (payment.amount > limit)
overLimitPayments.add(payment);
}
return overLimitPayments;
}

And the bad thing is that we've all gotten used to that horrible casting syntax. With Java 5 we could change this function to something like this:

    public List<Payment> findAllPaymentsOverLimit(
List<Payment> payments,
int limit)
{
List<Payment> overLimitPayments
= new ArrayList<Payment>();
for (Payment payment : payments) {
if (payment.amount > limit)
overLimitPayments.add(payment);
}
return overLimitPayments;
}

And that's much better, right?

My problem is with the more advanced uses of this new tool. I'll admit that I haven't fully understood this, but if you want to create code that must accept a typed collection or even worse a map, you'll have to learn the more advanced syntax where
List<? extends Class>
or
List<? super Class>

This is where it gets hairy, and where I start to think it might just not be worth it. On the other hand, I could leave that problem to the framework makers.

What have I been doing?

As can be seen from the blog it has been quite a while since my last post. I could always say that I've been busy (which is true), or that I haven't had that much to say, but that would just be excuses.

In these past months I've been busy working on getting more agile practices accepted at work. Ever since our sessions with Eric Evens and his guys, I've been convinced that we must change the way we develop software. The full implications of this did not register until I experienced the talk by Robert C. Martin at JAOO last autumn. Since then I've been devouring everything I could find on agile development, and it has been my main focus. I've also tried to speed up the process of change in my company, but as all big corporations it is slow.

I have, however, also found the time for some coding. God forbid I should forget how to do that. At work I've been busy doing some integration work, so it has been a lot of Java and XML. At home I've found just a little time to play a little bit with Ruby and Java 5 (more on that later).

Well, lets hope the next post doesn't delay as long as this one. See you.