Archive for the 'Programming: Java' Category

@attr in Java 1.5?

Friday, March 2nd, 2007

I wandered into a religious war at work today over the merits of pedantically Javadoc-ing even the most trivial methods, such as getters and setters. One side argued that documenting them was useless and should be omitted unless there was something meaningful to say, such as about possible side effects or possible ranges of values. The other thought that if you’re going to document at all, it’s better to be as complete as possible, because incompleteness signals laziness or poorly thought-out code. As we talked about it, I thought that I’d hit on a fantastic idea: to use Java 1.5 annotations to mimic Ruby’s @attr feature (which automatically creates getters and setters for instance variables). In other words, something that would take an instance variable declaration like

@attr private int foo;

and automatically generate

public void setFoo(final int newFoo) { foo = newFoo; }

and

public int getFoo() { return foo; }

Big deal, right? Of course, most IDEs can do something like this automatically when you add an instance variable. But what if it could also take the instance variable’s comment and turn it into appropriate comments for the getter and setter, too? Alas, it turns out that annotations can’t be used to generate code; they can simply be accessed in order for a tool or caller to do something useful. Ah, well, another missed opportunity for Java.

A Java ‘aha!’ moment

Wednesday, October 11th, 2006