Here is a typical way to achieve this:
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"); }
I think this solution is ugly. Your methods are quickly populated with template code that checks the valid contract of input parameters, obscuring the heart of the method.
Here is what I would like to have:
public void myContractualMethod(@NotNull @NotEmpty final String x, @NotNull final Set<String> y) {
If these annotations look like the JSR 303 / Bean Validation Spec, it's because I borrowed them. No wonder they don't seem to work that way; they are intended to annotate instance variables, and then run the object through a validator.
Which of the many default Java development schemes provides the closest functionality to my How-To example? Excluded exceptions must be runtime exceptions (e.g. IllegalArgumentExceptions), so encapsulation is not interrupted.
java validation annotations design-by-contract
rcampbell
source share