Search code examples
javaassert

What are the benefits of Assert statement?


What are the benefits of Assert statement really. I don't get why do I need to use it. I read nearly 100 questions/answers about assert statement but still no idea about what are the benefits of it. There are too many conflicts about this statement I think.

For example some people says "Never use it in production" but some people says "You can use them in production level". Some people says "Always handle assertionErrors in production" but some people says "Never and ever handle assertionErrors either in production or development level".

Why this is an incorrect usage for example https://stackoverflow.com/a/2758262/1379734


Solution

  • Why would this be considered incorrect?

    public int pop() {
       // precondition
       assert !isEmpty() : "Stack is empty";
       return stack[--num];
    }
    

    The assert is supposed to express an invariant condition. If pop() were a private method, then you could expect that it should only ever be called by code that checks for an empty stack. Because this method is public, you have no control over what assumptions can be enforced in the caller. In this case, a stack underflow should result in an Exception.

    Again, assert is a declaration of something that must be true, not something that may be true. "May" conditions should be enforced through other run-time checking and not declared in asserts.

    Whether or not to enable assertions in production is subject to preferences. The argument for doing so is that asserts should never fail, so they should be safe in production. The arguments against doing so are the performance penalty (some assert conditions can be expensive to calculate), and the disruptive nature of throwing Error throwables.