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.

  • Deely
    link
    fedilink
    arrow-up
    1
    ·
    1 year ago

    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.

    • JackbyDevOPM
      link
      fedilink
      arrow-up
      2
      ·
      1 year ago

      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.