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

Java

1385 readers
1 users here now

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

founded 1 year 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
[–] [email protected] 3 points 1 year ago (3 children)

It always felt like they were a relic from an older version of Java. I have used it once during a university lecture and that was it. I think they are also not so useful if you have good unit tests and have well-structured code. In most cases where they would be useful, it is probably still safer to use actual if statements, even if that adds more boilerplate to the code.

[–] JackbyDev 2 points 1 year ago (2 children)

used it once in university

In university they always seem so intent to teach you everything. I remember seeing someone ask about some question that involved the return value of the assignment operator. I was like "look whatever you do please don't use this in the real world" lol. It may not have been Java.

[–] Clifspeare 1 points 1 year ago (1 children)

I mean, it's still a fairly common pattern to use the l-value yielded by the assignment operator in for-loops in C.

[–] JackbyDev 1 points 1 year ago

Can you give an example? I'm not sure I follow.