Alternatives to Assert

3.6k Views Asked by At

The reasons I am dissatisfied with assert keyword in Java are

1) it's disabled by default, so it is a headache to make sure it's enabled when I want it to be

2) its behavior is rather rigid (I would want some inversion of control, ideally); but that's not terribly important.

Some of the alternatives I can think about:

  1. JUnit's assertEquals() and such - good for tests, but can't use in main code
  2. Guava's preconditions - great, but no assertion methods per se.
  3. My own assertion library - I wrote it back in 1999, and back at the time it was great, but now I want to standardize.
  4. Anything else?

So.. to sum it up.. how do I assert in production code in a way that is not disabled by default?

(And yes, this may be considered an anti-pattern by some, but I do want at least some assertions in Production, even if assertion failures are just silently logged. I see some room for that even in shrink-wraps, and definitely in websites).

3

There are 3 best solutions below

1
On

I'd use Spring's Assert class, it includes a fairly extensive range of checks.

6
On

I am not sure if this is what you want, but I'm routinely using commons-lang Validate for many years already. Usually in public API methods/constructors to ensure that arguments are passed correctly. Not just notNull (see Lombok's @NotNull for this) but also noNullElements etc.

I especially like the <T> T notNull(T object) signature for immutables:

private final JSCodeModel codeModel;
private final String name;

public FunctionDeclarationImpl(JSCodeModel codeModel, String name,
        String[] parameterNames, JSSourceElement[] sourceElements) {
    this.codeModel = Validate.notNull(codeModel);
    this.name = Validate.notNull(name);
    ...
}

What are your requirements, actually?

1
On

JUnit's assertEquals() and such - good for tests, but can't use in main code

Nothing technically prevents you from using JUnit assetions (and/or Hamcrest matchers) in your main code. Just include the Junit jar in your classpath. It's usually not done but that's more of a convention than any technical limitation.

Java 7 also introduced Objects.requireNotNull(obj, message) and similar methods although not as full featured as JUnit assertions.

but I think if you want to go with a more standardized approach Guava's preconditions is probably best.