Questions about using `assert` in Java
-
liangchenblue at gmail.com
Sat Jul 15 23:09:48 UTC 2023
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> 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/20230716/a4bb6541/attachment.htm>
More information about the core-libs-dev
mailing list