Tuesday, July 29, 2008

Death by Annotations

Every so often I read how 'we're all going to be drowning in annotations' or how someone's 'annotations are exploding' and consequently how 'OMG annotations suck'. I'd agree it's a problem. But, seeing as how Metawidget is probably going to make it worse, not better, I thought I should offer a balanced view.

Here's the basic problem. Here's a piece of Real Code, from one of my production systems, that uses JPA, JAXB, Hibernate extensions and Metawidget:

@OneToMany( cascade = CascadeType.ALL )
@JoinColumn( name = "survey_id" )
@IndexColumn( name = "number", base = 1 )
@Cascade( org.hibernate.annotations.CascadeType.DELETE_ORPHAN )
@UiComesAfter( "dateExtension" )
@XmlElement( name = "question" )
public List getQuestions()
   return mQuestions;

A lot of people are going to look at that, think it looks really messy, and turn off. And I agree - it does look really messy. But it's important to consider what we've gained here, and what the alternative is:
  • it's less code, and more typesafe, than 4 separate XML configuration files

  • the metadata is closer to the thing the metadata is referring to

  • whilst it may seem like a lot of annotations for little actual code (the bit in bold), that's backward thinking: annotations are code, albeit declarative code. And it's a lot less code to write something declaratively than procedurally
So whilst I don't necessarily think annotations are as good as life can get, I do think they're better than anything we ever had before. The challenge now is how do we make them better?


Anonymous said...

I disagree, annotations seem harmless, but I'd prefer the 4 xml files. with annotations your code is only as flexible as its last compile. with external xml all you need to do is reconfigure for any reuse of the code. if I have 2 simultaneous uses of the same class for different purposes its not always possible to support with annotations. but it is with xml configs. code reuse is still important and annotations make that more difficult.