Rethinking the annotations

34 views
Skip to first unread message

vvessan

unread,
Feb 24, 2008, 7:49:14 AM2/24/08
to JSR-305: Annotations for Software Defect Detection
First of all I have to say I have no experience of how are proporsals
for JSR done (I'm just student), but I would like to present my point
of view on annotations as I use them for a long time in IntelliJ IDEA:

- the problem is that there could be really too much annotations for
various purposes
- i have found a presentation solving the same problem
http://wiki.glassfish.java.net/attach/FindBugs/Glassfish_FindBugs.pdf
- however proposed syntax for custom annotation seemed quite complex
to me

Here is my proporsal, similar to the one found in the presentation (i
will ommit some code like retention policy, target types etc. that
would make the code longer, also sorry for syntax mistakes writing
directly to post not copy from IDE):

- define common annotation for type contracts that could be used for
checking input parameters and returned values, like following:

public @interface TypeConstract {

Class<? extends TypeContractValidator> value(); // value specifying
which class can be used to validate the instance of class
}

public interface TypeContractValidator<T> {

void validate(T t) throws SomeValidationException; // or make the
exception runtime could be better
}

- now we can use this annotation for parameters, methods

public void method(@TypeContract(Positive.class) int value) {
}

public final class Positive implements TypeContractValidator<Integer>
{

public void validate(Integer i) {
if (i <= 0)
throw new RuntimeException();
}
}

- we can also use the annotation to create shortcuts for commonly used
contracts, example:

@TypeContract(NotNullConstract.class)
public @interface NotNull {
}

public final class NotNullContract implements
TypeContractValidator<Object> {

void validate(Object o) {
if (o == null)
throw new NullPointerException();
}
}


... i think the advantage of such approach is that:
- it makes it really simple to define custom validation on types
- it can be used in runtime
- allows writing shortcuts for oftenly used types
- minimizes the number of annotations that would have to be included
in the specification

... but it doesn't cover everything of course, it's just checking for
types
Reply all
Reply to author
Forward
0 new messages