@Syntax

I like programming in Java because it is a strongly typed language, i.e some classes of programming errors are discovered at compile time instead of at run time. The generics feature introduced in Java 1.5 is a great improvement that add another class of errors that can be discovered at compile time but at the same time some additions to the Java languages introduced new potential programming errors that cannot be easily detected at compile time.

The oldest feature with this problem was I think SQL. The SQL requests are stored in String objects and a syntax error can be detected only when the program itself runs – at best it can be detected when the program starts but in the worst case, e.g. if a SQL request is no used very often, it could be discovered too late. Sure it is possible to write unit tests to detect the error, but this a little bit overkill just to verify that the syntax is correct. Other examples of String objects containing structured text are used in MessageFormat, Pattern (regex), Formatter, etc…
So I wrote this small java annotation named Syntax. The idea is to annotate a String containing structured text with the type of syntax used. At compile time, it is then easy to check that the content of the String is valid. Here is the definition of the annotation:

public enum Language { REGEX }

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public @interface Syntax {
public Language value();
}

An annotation can then be added to a String constant:

@Syntax(REGEX)
private static final String MY_PATTERN = "[abc";

It is then simple to write an annotation processor that retrieve the value of the String and use Pattern.compile to check the syntax. The implementation for Pattern, MessageFormat, DateFormat and Formatter is only 72 lines. Adding SQL is a little bit more tricky, as there is nothing in the JVM to verify the SQL syntax. A simple solution is to use JavaCC that have free grammars for SQL and other languages.

The main limitation is that this annotation can be used only on a String constant, so the code needs to be slightly rewritten to take advantage of this technique.