Search code examples
javaexceptionjakarta-eeassertassertion

Programming with assertions in Java


I wonder if a lot of people program in Java with assertions. I think this can be very useful on large projects without enough written contracts or outdated contracts. Particularly when you use webservices, components, etc.

But I have never seen any project using assertions (except in JUnit/testing tests...).

I've noticed that the thrown class is an Error and not an Exception. Why do they choose an error? Can it be because an exception could be unexpectedly caught and not logged/rethrown?

If you develop an application with components, I wonder where you put the assertions:

  • On the component side, just before returning the data through the public API?
  • On the component client side? And if the API is called everywhere you set up a facade pattern that will call the assertion mechanism? (Then I guess you put your assertions and facade on some external project and your client projects will depend on this assertion project?)

I understand how to use assertions, and when use them, but just wonder if some people have recommendations based on a real experience of assertions.


Solution

  • By the way, do you refer to assert in Java?

    I personally find assertions especially useful for invariants. Take into account that assertion checking is turned off by default in Java. You have to add the -ea flag to enable assertion checking.

    In other words, you can test your application in a kind of debug mode, where the program will halt once an assertion is broken. On the other hand, the release application will have its assertion turned off and will not incur time penalty for assertion checking. They will be ignored.

    In Java, assertions are far less powerful than exceptions and have totally different meanings. Exceptions are there when something unexpected happens and you have to handle it. Assertions are about the correctness of your code. They are here to confirm that what 'should be' is indeed the case.

    My rough policy, especially when working with many developers:

    • public methods: always check arguments and throw IllegalArgumentException when something is wrong
    • private methods: use assertions to check arguments against null pointers and so on
    • complex methods: intermediate assertions to ensure that the intermediate results satisfy requested properties

    ...but actually, I use them sparsingly. Just where it's critical or error-prone places.