Questions about using `assert` in Java

Daohan Qu quadhier at outlook.com
Mon Jul 17 13:09:29 UTC 2023


Hi Liang,

Thank you for your response! The provided guidelines are quite helpful. I have
noticed that different packages in JDK use the assert​ keyword to varying degrees.
I wonder if this is more a matter of developer preference (if it is not the performance
reason mentioned by Alan). :P

Regards,
Daohan

________________________________
From: liangchenblue at gmail.com <liangchenblue at gmail.com>
Sent: Sunday, July 16, 2023 7:09
To: Daohan Qu <quadhier at outlook.com>
Cc: core-libs-dev at openjdk.org <core-libs-dev at openjdk.org>
Subject: Re: Questions about using `assert` in Java

Hi Daohan,
assert keyword is safely usable within production code. I don't think it has a significant performance impact if it is not enabled. Thus, you should not enable it in production unless you are debugging.

A package that uses assert extensively is java.lang.invoke package.

For me, these are the general notes for using assert:
1. They should not perform side-effects, such as changing variables. Having -ea, -esa and no flag run differently is definitely not desirable.
2. assert should not be used to defend against incorrect user inputs; it should only be used to ensure the correctness of internal states of your program, as assert is optional.

Chen Liang

On Sun, Jul 16, 2023 at 12:54 AM Daohan Qu <quadhier at outlook.com<mailto:quadhier at outlook.com>> wrote:
Dear developers,

I'm a graduate student doing software engineering research.
Recently, I came across some interesting facts about Java assert​
statements and have a few questions to ask.

Although the assert​ keyword has been around for a long time and
is handy for invariant checks, it does not seem to be widely used.
For example, in the famous j.u.c​ packages, nearly all assert​
statements are commented out [1].

My questions are, should assert​ be heavily used in Java programs,
especially in production code? And should we enable them in the
production code?

By the way, I have read a useful article about using assertions in
Java [2], but it does not provide clear answers to my questions above.

Thank you in advance!

[1] https://github.com/search?q=repo%3Aopenjdk%2Fjdk+assert+path%3A%2F%5Esrc%5C%2Fjava.base%5C%2Fshare%5C%2Fclasses%5C%2Fjava%5C%2Futil%5C%2Fconcurrent%5C%2F%2F&type=code
[2] https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html

Regards,
Daohan Qu

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20230717/57c9e3ab/attachment.htm>


More information about the core-libs-dev mailing list