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.

  • TomM
    link
    21 year ago

    I was excited to use assert when I learned about it. I thought it would be ideal for short, clean guard clauses at the top of methods, to fail early on invalid data.

    Once I realized that they’re configurable and generally seemed to be off by default, they seem completely useless for that scenario. Doubly so when you’re working in an environment where you don’t control the server environment.

    • JackbyDevOPM
      link
      11 year ago

      I still think it can be useful but it really needs to be for things that can’t be true as opposed to things that shouldn’t be true. Like imagine this pseudocode (I have no idea off the top of my head if there is some extreme edge case where this does not hold true lol)

      int i = someInt();
      i = i % 3;
      assert 0 <= Math.abs(i) && Math.abs(i) < 3 ;
      
      • TomM
        link
        11 year ago

        I would avoid using it that way too. Seems like it could be a source of confusion in the future (another dev may assume it offers protection it doesn’t), and I would guess most IDEs would flag it as unnecessary.

        I do my best to avoid huge if blocks, but when they do happen, I prefer a small, simple comment noting the purpose.