Thursday, August 23, 2007

Assertions Vs Exceptions

its definetly something to think about! some people are so fascinated with exceptions, they tend to over use it . i even have learned about exceptions before assertions. to clear things out i had a discussion with our senior developer, Michal, which helped me reach the following conclusions:
  • Exceptions should be used for exceptional occasions only. stuff that is considered such : trying to send information over the network failure due to a none expected network error.
  • Exceptions should not be used to capture developers errors, as these are not exceptional scenarios/errors .....and could be avoided .
  • a good example of a case when exceptions should not be used is when i user does clicks somewhere on the screen that is exceptional, like when the user does some random mouse clicks sequence in random places in the screen, this should be handled gracefully not by raising an exception.
  • on bad thing about exceptions is that if some funtions dont explicitly catch the exception they might have code that is gettting executed anyway even though an exception was raised but it was never caught in this function (could be in another thread) .
  • Assertions are particularly made to check for programmers errors.
  • checking the passed args to a function if they are viable, should be done by an assertion . this will help identify any future problem arising from some not so great code handling in other classes ( callers of the function) . this way the prblem could be traced back easily with less debugging required .
  • ummmm....what else ? ............well how often should we validate the input of a function? is it exhaustive to do it for every function on every argument ? thats another question, i came into the understanding that :
    • public functions ( could be called from outside of the class/module/namespace/scope should never ever tus t the callers blindly and completely.
    • Private functions can be guranteed to put trust into callers, mainly because of the fact every class should know how to modify its state . plus if the public functions are validating input then when they call internal private functions they would be within the valid region .
  • The last thing here to mention is that even the funtion is asserting the inputs it should afterwards restrict the processing code within an if statement, which makes sure that this code is never executed on bad input.

thats all i can recall, which means thats everything that got such ion my head , i.e what i have learned today . assert on public functions then execute only on good input .