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:
- JUnit's assertEquals() and such - good for tests, but can't use in main code
- Guava's preconditions - great, but no assertion methods per se.
- My own assertion library - I wrote it back in 1999, and back at the time it was great, but now I want to standardize.
- 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).
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.