javaassertdesign-by-contractpost-conditions

Design by contract and assert statements


I am interested in the Design by Contract approach. It seems that for preconditions checked exceptions must be used to enforce them.
But for post-conditions and class-invariants I think that assertions are preferred.
Am I right? If I am correct, why for post-conditions and class-invariants assertions which may be disabled are allowed? Shouldn't post-conditions and invariants also be enforced?


Solution

  • Post conditions and class invariants on a component can only fail if the component itself is written incorrectly. Unit tests should catch all of these. It's permissible, of course, to actually check them in production, but this isn't necessarily worth the performance tradeoff.

    On the other hand, preconditions can fail if the users of that component are incorrect. Tests on the component itself cannot check these, so it's necessary to fail more actively so that those unit tests fail.