A lot of my functions have a whole load of validation code just below the declarations:
if ( ! (start < end) ) {
throw new IllegalStateException( \"S
Aspect oriented programming can be used for such a problem. Method calls can be intercepted checking for the invariant. Pointcuts and advices are configured in a declarative way. Spring and Guice make usage of AOP straightforward.
Here's an example in Guice.
Check out the Cofoja project which provides contracts for Java through annotations. It provides Pre-/Postconditions and Invariants. Also in contrast to other Java implementations it correctly handles contracts defined in parent classes/interfaces. Contract evaluation can be enabled/disabled at runtime.
Here is a code snippet from their tutorial:
import com.google.java.contract.Invariant;
import com.google.java.contract.Requires;
@Invariant("size() >= 0")
interface Stack<T> {
public int size();
@Requires("size() >= 1")
public T pop();
public void push(T obj);
}
If I find myself repeating the same boiler-plate precondition checking code within a class, I refactor my code to reduce the duplication and to increase abstraction by extractung the repeated code into a new (static private
) method. I use the Java-7 Objects.requireNonNull
method for null
checks.
For input validation, you can also use Apache Commons Validator.
Note that input validation should always be enabled. Hence it is conceptually very different from assertion checking (as, e.g., in Eiffel), which can be optionally on/off -- see the answer to this related stack overflow question When should I use Apache Commons' Validate.isTrue, and when should I just use the 'assert' keyword?
The JUnit package has constructs like assert that would aid in doing such condition check.
How about assert start < end
. Have a look at the documentation.