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.

  • JackbyDev@programming.devOPM
    link
    fedilink
    arrow-up
    2
    ·
    1 year ago

    What’s interesting is that the document seems to be aware of this and suggests not using it for full desogn-by-contract style pre/post conditions but does say it is fine for that on private methods.

    But I’ve found myself so many times seeing things in production that I can’t replicate locally (at least not easily) that I can’t really say I’d want code like this (even if it was disabled in all environments except for unit testing). I just feel like it would throw people off. “Well it can’t be that this private method is getting a negative number because there is an assertion. Sure, they’re disabled, but a test would’ve ran into it. I can even easily see where this private method is called from.” Then the problem ends up being that a negative number somehow got there lol. If that assertion had not been there then maybe people would’ve tried to see if that was the case first. Better yet, have a trace level log message for parameters then enable it for that one class.