It always felt like they were a relic from an older version of Java. I have used it once during a university lecture and that was it. I think they are also not so useful if you have good unit tests and have well-structured code. In most cases where they would be useful, it is probably still safer to use actual if statements, even if that adds more boilerplate to the code.
You are not wrong that they are in a way "executable comments". Just like comments they are intended only for development/debugging and can't (shouldn't) have any influence on production code.
For example, in your sample code the if
is unnecessary, because condition
can't be (should not be) true
. If it were, it would be a bug. Instead it should be written as:
assert !condition;
// Very long block of code
If the condition can ever be true
then you shouldn't be using assert
.
I could be wrong but assert used practically everytime while writing unit / integration tests. Practically every test contains form of asset, could be standard Java assert keyword, or, more often JUnit Assert class.
I've never seen a unit test using the assert keyword, only the JUnit Assert class methods. It throws AssertionError so it is like the assert keyword but can't be disabled like the assert keyword.
I think the idea was that you could run extra checks by in a QA environment without bearing the runtime cost of all the if (QA)
tests in your production code.
No, I've never used it. Our company style guide discourages it because even in QA it would be too easy for some config to get lost/forgotten and give unexpected behavior. What if you're silently skipping asserts during your CI smoke tests because the jvm flag was missed, but now you think you've got the extra protection of those asserts?
Java
For discussing Java, the JVM, languages that run on the JVM, and other related technologies.