Navigation

Comparison of Ways to Check Preconditions in Java

BY MARKUS SPRUNCK

This article focuses on preconditions which are directly part of the source code. It doesn't cover other approaches which use annotations and aspect oriented programming.

The use of preconditions, post-conditions and invariants is extremely helpful to develop maintainable code. Unfortunately, we find preconditions quite seldom in real world applications. In some cases you can read correct preconditions in JavaDoc comments. The big disadvantage of JavaDoc comments are that (i) they just get outdated in cases the implementation changes and (ii) most of the developers just don't read them or read them too late.

Example Code

To compile the code you will need the followinglibraries:

commons-lang3-3.1.jar (315,805 bytes)

guava-14.0.1.jar (2,189,117 bytes)

spring-core-3.2.2.RELEASE.jar (866,788 bytes)

In the example code you may see four different ways to directly implement preconditions and the use of asserts. I can't recommend asserts to check preconditions, but you may mix asserts with the four other approaches.