Saturday, February 25, 2012

[Java] Assert and Exception

How to use?
Use assert /ə'sə:t/ as a comment, to TEST a comment
You should now use an assertion whenever you would have written a comment that asserts an invariant.
   if (i % 3 == 0) {
    } else if (i % 3 == 1) {
    } else {
        assert i % 3 == 2 : i;
assert for test/debugging, not error-checking
  • use exceptions when checking parameters passed to public or protected methods and constructors
  • use exceptions when interacting with the user or when you expect the client code to recover from an exceptional situation
  • use exceptions to address problems that might occur
  • use assertions when checking pre-conditions, post-conditions and invariants of private/internal code
  • use assertions to provide feedback to yourself or your developer team
  • use assertions when checking for things that are very unlikely to happen otherwise it means that there is a serious flaw in your application
  • use assertions to state things that you (supposedly) know to be true
In other words, exceptions address the robustness of your application while assertions address its correctness.
Assertions are designed to be cheap to write, you can use them almost everywhere and I'm using this rule of thumb: the more an assertion statement looks stupid, the more valuable it is and the more information it embeds. When debugging a program that does not behave the right way, you will surely check the more obvious failure possibilities based on your experience. Then you will check for problems that just cannot happen: this is exactly when assertions help a lot and save time.

No comments: