Here is the typical way of accomplishing this goal:
public void myContractualMethod(final String x, final Set<String> y) {
if ((x == null) || (x.isEmpty())) {
throw new IllegalArgumentException("x cannot be null or empty");
}
if (y == null) {
throw new IllegalArgumentException("y cannot be null");
}
// Now I can actually start writing purposeful
// code to accomplish the goal of this method
I think this solution is ugly. Your methods quickly fill up with boilerplate code checking the valid input parameters contract, obscuring the heart of the method.
Here's what I'd like to have:
public void myContractualMethod(@NotNull @NotEmpty final String x, @NotNull final Set<String> y) {
// Now I have a clean method body that isn't obscured by
// contract checking
If those annotations look like JSR 303/Bean Validation Spec, it's because I borrowed them. Unfortunitely they don't seem to work this way; they are intended for annotating instance variables, then running the object through a validator.
Which of the many Java design-by-contract frameworks provide the closest functionality to my "like to have" example? The exceptions that get thrown should be runtime exceptions (like IllegalArgumentExceptions) so encapsulation isn't broken.
I would use Parameter Annotations, Reflection and a generic validator class to create an app-wide facility. for example, you can code a class method like:
.. myMethod( @notNull String x, @notNullorZero String y){
}
The class methods are "marked up" to annotate their contract requirements. Use reflection to automatically discover the params, their values and annotations. Send it all to a static class to validate and let you know the outcome.
If you're looking for a fully fledged design-by-contract mechanism I'd take a look at some of the projects listed on the Wikipedia page for DBC.
If your looking for something simpler however, you could look at the Preconditions class from google collections, which provides a checkNotNull() method. So you can rewrite the code you posted to: