Questions about using `assert` in Java
Pavel Rappo
pavel.rappo at oracle.com
Mon Jul 17 11:29:38 UTC 2023
In this thread, Alan has already pointed out possible runtime cost of Java assertions. But as far as the general idea goes, I find assertions to be very helpful.
There have been studies looking into correlation between assertion density and fault/defect density. Here's one such study: "Assessing the Relationship between Software Assertions and Code Quality: An Empirical Investigation" [^1].
Modern Java IDEs make use of assertions. IDEs analyse and highlight assertions that are always false or always true, helping the author to reason about their program as they type it.
That said, Java assertions are a bit anaemic. I wish they generated helpful messages automatically (though I realise that it might have security implications). Consider these assertions:
* assert x >= 0;
* assert x && y;
* assert a == b;
* assert ( f ? foo() : bar() );
I would like the compiler to transform those into these (respectively):
* assert x >= 0 : x;
* assert x && y : x + ", " + y;
* assert a == b : a + ", " + b;
* assert ( f ? foo() : bar() ) : f;
-Pavel
---
[^1]: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-2006-54.pdf
> On 15 Jul 2023, at 17:53, 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
>
More information about the core-libs-dev
mailing list