dagblog.
← Archive

A quick reminder about assertions


When Java 1.4 introduced assertions, many people probably expected the keyword assert to become a fixture in source code. I don’t know about you, but as far back as I can remember I don’t think I’ve ever used assert. You could say that proves nothing, but worse still, I don’t think I’ve even seen assert in the source of open-source libraries.

It’s a little surprising, because assert has its uses, if only in place of comments like “execution never gets here.” I have three theories for why assert never caught on among us Java developers.

Marketing

Java 5, 6 and 7 all seemed to get plenty of hype. We were inundated with news of what each release would include or leave out, and there were learned debates about why a particular feature made the cut. Sun didn’t put much effort into promoting assertions. If all the source code in Sun’s tutorials had been full of assert, I probably wouldn’t be writing this now.

Enforcement

One big drawback of assert is that you can have it in your code but still need to set a special JVM flag to enable it. Try remembering to do that every time. It would be better to enable assert at the compiler level and have it on by default. You’d have to turn it off explicitly. Here’s what I consider a weak defense of using a JVM flag.

Unit testing culture

I think Java inherited the assert construct from C, where it’s a fairly well-established convention. At least the programmers I usually discuss assert with came to Java from C. But by the time Java added it, unit testing was already firmly established. The things you’d incidentally check with assert were explicitly checked by unit tests, and that’s become something of a convention in Java.

Medium version

Related articles

Related CZ Podcast episodes