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.
Not a fully working solution, but JSR-303 has a proposal for a method-level validation extension. Because it's just an extension proposal just now, implementations of JSR-303 are free to ignore it. Finding an implementation is a little more tricky. I don't think Hibernate Validator supports it yet, but I believe agimatec-validation has experimental support. I've not used either for this purpose so I don't know how well they work. I'd be interested in finding out though, if someone gives it a go.
There is a small Java Argument Validation package, implemented as Plain Java. It comes with several standard checks / validations. And for those cases where someone need its own more specific validations, it comes with some helper methods. For validations that occur multiple times, just extend the interface ArgumentValidation, with your own And create the implementing class that extends from the class ArgumentValidationImpl.
Jared pointed you to various frameworks that add support for DBC to Java.
What I found to work best is: simply document your contract in the JavaDoc (or whatever Documentationframework you use; Doxygen has support for DBC tags.)
Having your code obfuscated by a lot of throws and checks of your arguments isn't really helpful to your reader. Documentation is.
This doesn't directly answer your question, but I think that part of your problem is that you are overdoing the validation. For instance, you could replace the first test with:
and rely on Java to throw a
NullPointerException
ifx
isnull
. You just need to alter your "contract" to say that NPE is thrown for certain types of "you called me with illegal parameters" situations.If you're using Java 8, lambdas can be used to create a very elegant and readable solution for validation:
You use it like:
The exception will look like:
The first nice thing is that the above Assert class is all that's needed really:
Of course
that()
can be implemented in a number of ways: with a format string and arguments, to throw other kinds of exceptions, etc.It does not, however, need to be implemented to perform different tests.
Not that you can't pre package tests if you like to:
I have no clue if this is bad for performance or not a good idea for some other reason. (Just started looking at lambdas myself but the code seems to run as it should...) But I like that
Assert
can be kept short (no need for dependencies that may not be crucial to the project) and that the tests are very visible.Here's a method for a better error message:
You call it like:
And out comes:
Update: If you want to use the
x = Assert...
construction with a prepackaged test, the result will be cast to the type used in the prepackaged test. So it must be cast back to the type of the variable...SomeClass x = (SomeClass) Assert.that(x, isNotNull)
I've seen a technique by Eric Burke that is roughly like the following. It is an elegant use of static imports. The code reads very nicely.
To get the idea, here is the
Contract
class. It is minimal here, but can be easily filled out as needed.And here is an example usage. The
foo()
method illustrates the static imports:Note: when experimenting, note that there may be a bug around doing this in the default package. I've certainly lost brain cells trying it.