this post was submitted on 13 Jun 2023
6 points (100.0% liked)

Java

1414 readers
1 users here now

For discussing Java, the JVM, languages that run on the JVM, and other related technologies.

founded 2 years ago
MODERATORS
 

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.

you are viewing a single comment's thread
view the rest of the comments
[โ€“] terebat 1 points 2 years ago (1 children)

That latter part is the same reason we mainly just use it in unit tests, and not much else. It's such a baffling situation when there's an assert, but the code still executes despite the assert. Debugging an incident or issue just becomes super annoying when that can be the case.

[โ€“] JackbyDev 2 points 2 years 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.