Search code examples
javaassertpreconditionspost-conditions

Precondition and postcondition checks in public methods


I was reading the Oracle documentation about using the assert keyword to verify method preconditions and postconditions.

The document says that it's fine to use the assert keyword to verify postconditions for public methods but you should only use the assert keyword to verify preconditions for private methods.

Why is this?


Solution

  • A complete answer instead of dumping it in comments.

    Why shouldn't I use assertions for argument checking in public methods ?

    Assertions relying on assert can be disabled by a JVM flag. Therefore, there's no way to guarantee assertions will indeed run when your users run your code. That's why it's bad to make promises to throw validation errors in your API if you can't actually guarantee it will happen. Therefore, you allow your users to call you with invalid parameters without throwing exceptions to warn them. You should use runtime exceptions instead.

    So then, why is it fine to use it for post-conditions in public methods ?

    The doc you quoted defines pre and post conditions as follows:

    Preconditions — what must be true when a method is invoked. Postconditions — what must be true after a method completes successfully.

    You can see that pre-conditions depend on the caller while post-conditions depend on the callee. If pre-conditions were met, the only reason why a post-condition could fail is because the code in the method is buggy. It isn't a user mistake, it's a problem with the library itself. I'm guessing that's why the doc believes it's less problematic to end up with disabled post-conditions assertions.

    I'm not sure I personally agree because if post-conditions are not met it probably means the contract of the method has been violated and execution should stop. Depends how critical the post-condition was. API writers may want to check some ratio is optimal for performance at the end of a dynamic array resize, but not necessarily throw an exception if it was not the case as the program would still behave as expected even with a sub-optimal ratio.