← Back to context

Comment by rwmj

3 days ago

I'm quite surprised that he said asserts are not found in production code. Is that really so? I rarely write Java, but in C code we use asserts (in production code) all the time. It's not uncommon for functions to contain 2 or 3 asserts.

I very rarely see assertions in "real" Java code; I think the author is right - in fact the place I see them the most often is in unit tests where they've been used by mistake in place of an assertion library's methods!

I don't know why they're not more popular.

I think they're used less because the main reason for using them in C isn't a consideration in Java, and also they don't accomplish the same thing.

In C, asserts are used as sanity checks, and when one is violated, there's often reasonable suspicion that that memory corruption has occurred, or that memory corruption will occur if the code proceeds in the current state. Aborting the process, leaving a core dump for analysis, and starting fresh is often the safest thing to do to avoid the unpredictable results of corrupted state, which can be insidiously subtle or insanely dramatic. In my experience writing server-side C++, we always ran it in production with asserts enabled, because code that continued to run after memory was corrupted led to the the bugs that were the most destructive and the most mysterious.

Memory corruption is rare enough in Java that 99.9% of code completely ignores the possibility. Also, if you did suspect memory corruption in a Java program, an assert wouldn't help, because it would only throw a runtime exception that would probably get caught and logged somewhere, and the process would continue serving requests or whatever else it was doing.

If you're only doing like CRUD endpoints, they may be less useful, but that's hardly the extent of Java production code. I certainly use asserts in production code quite a lot in Java, though the use biases toward more low level functions, rarely in high level application logic.