Good annotations: clean code
2009/03/14 Leave a comment
Annotations are a fantastic tool introduced in Java 1.5 that allows you do add some extra information to a class, method or field.
I thought of it lots of times, but I’m sure we all did: a class is a class, it does its stuff, it has its fields and methods, but it would be nice to add some extra information to trigger some events, in certain conditions. I mean, not variable, mutable, changeable info, just static stuff.
Let me do a very simple example. Image a stupid javabean dump function. It gets a generic bean, and prints the values returned by the getters (with the technique I explained in “Coffee Mug Reflections part 2″)
class RandomBean{ [...] public int getAVal(); public int getBVal(); }
The function we’re talking about would print the results of getAVal and getBVal. Say, “1″ and “2″? Meaningless data. Even if we printed the methods name “getAVal: 1″ and “getBVal: 2″: useless. Even if the function name were “getArctanOfC”, the list of methods would be almost useless. How can we associate a comment to methods? Let’s annotate it!