tags:

views:

238

answers:

2

Sometimes data structures should have certain relationships that can't be directly described in Java, but that are good to check as early as possible when code is edited. Classic examples are that an array is big enough or that enums in different modules have corresponding members.

BOOST provides a fine "static assert" facility in C++ that even provides half-decent errors when assertions fail; does anyone know how to build a compile-time assertion facility in Java?

Edit: I just saw a perfect example: this class from Eclipse has two constant arrays that are assumed to be the same length. If that were my code, I'd like the compiler to tell me if they have different lengths.

+1  A: 

Incremental compilers that come as part of IDEs like Eclipse can be configured to throw warnings or errors on finding code that is legal java, but may cause problems at runtime. You can ratchet these settings up as far as you like, although it may start to get invasive and annoying.

skaffman
+5  A: 

There are a number of tools you can use

  • PMD
  • Checkstyle
  • FindBugs
  • Validate methods in Jakarta Commons-lang (we use this instead of assert and leave it in)
  • Cobertura/EMMA (for Code coverage).

A combination of these and good unit tests will catch the low hanging fruit (and some of the higher stuff as well)

Fortyrunner
+1 for using unit tests as essentially a step which is closer to compile time than execution time.
Jon Skeet