Assertions being built into Java is nice and they’ve been around since version 1.4. They predate type parameters! I have never seen them being used and the reason always seems to be that because you can’t count on them being turned on because they’re off by default.

The only theoretical use I can think of it for “executable comments”, as in something like the example below, but they’re annoying as the IDE will usually complain that it is always true (with no way to specifically disable warning for always true assertions, only always true conditions in general).

if (condition) {
  // Very long block of code
} else {
  assert !condition; // Primarily a reminder for when the if condition is not easily seen
}

Here it doesn’t matter if the assertion is executed or not because it is just a reminder. The idea being that code sticks out more than a comment.

  • RoToRa@discuss.tchncs.de
    link
    fedilink
    English
    arrow-up
    3
    ·
    2 years ago

    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.

    See also https://stackoverflow.com/a/2758645/318493

    • JackbyDevOPM
      link
      fedilink
      English
      arrow-up
      2
      ·
      2 years ago

      Sorry, the example wasn’t clear, I meant to have a normal if statement for normal things and then assert that the condition that you just checked in the if is false in the else before doing what you’d normally do in the else block. Something like this.

      if (isEven) {
        log.info("it's even");
      } else {
        assert !isEven;
        log.info("it's odd");
      }
      

      Again, not a great example because the code is short enough to clearly see the entire thing, but it better illustrates what I meant.

      • RoToRa@discuss.tchncs.de
        link
        fedilink
        English
        arrow-up
        1
        ·
        2 years ago

        To be honest that doesn’t change anything about what I said. The assertion condition must never be true at runtime. If it ever can be, then it’s a wrong use of assert.

        • JackbyDevOPM
          link
          fedilink
          English
          arrow-up
          1
          ·
          2 years ago

          In that example it can’t be true in the else block (assuming it is a local variable).