Features of Java generics

By | May 29, 2015

Java generics is a great feature introduced in Java 5, but it’s not that type safe that you would assume. The following example was found in our test code.

dto.setFailingTask(new ArrayList(Arrays.asList("Task1", "Task2"));

where the setter looks like the following:

public void setFailingTask(List<Task> aTasks) {
  tasks = aTasks;
}

So what’s going on here? The first thing to notice is that this did not cause a compile error or warning in that case. The error and warnings was in fact turned off in our development environment (we manage the settings in our source control).

If we look at the harm it did instead. Turns out that the DTO is used to present a html based report to the user. With it the tests are checked against a XSD-Schema. With the above code the test passes but when we are using it correctly it will fail. The schema definition wants a string representation of the task, but when we are using the actual task object it we be a task representation. In production this behaviour caused a bug with no tasks showing in the report.

So this test, written correctly would have found the bug and we could have fixed it instantly. So to allow this usage of generics really misleads the user and caused a serious bug in the end. The only reason that this is allowed is to be backwards compatible.

We would also have found it if we had configured the compiler level to error or at least warning.

So to prevent this error we need both more experience in the Java language pitfalls/features and a more restrictive compiler configuration. I also believe that when we are writing tests we should avoid using such Java features.

Leave a Reply

Your email address will not be published. Required fields are marked *