Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put Assertions?

Having assertions for unexpected conditions is considered to be good defensive coding practice. I happen to place assertions whenever i think something unexpected may happen, but that now seems to be an overkill to me.

Additionally, sometimes mild unexpected conditions that don't necessarily lead to crash may even cause failure on customer end.

Is there a hard and fast rule to put assertions?

Thanks.

like image 467
sud03r Avatar asked Jan 31 '11 07:01

sud03r


2 Answers

The main difference between when to use assertions and exceptions:

  • Use an assertion to catch programming errors. Assertions should never happen if the code has been written correctly.

  • Use exceptions to catch run-time errors caused by unexpected environment.

  • If your program reads a script or contents from a file and they do not match the expected format, I consider that is a runtime condition therefore an exception.

You may decide, for debugging purposes, to use an assertion in the place where an exception is thrown simply to be able to work out more easily where it got thrown, although you can use exception macros that insert FILE and LINE into the message to do that too.

like image 187
CashCow Avatar answered Oct 07 '22 16:10

CashCow


Where to put assertions?

What is often overlooked is that an assert can also serve as a documentation aid.

So don't only test for the 'unexpected', also use them to express your assumptions (invariants) at critical points in your code. Like assert(high >= low)

And of course make them conditional, as others have pointed out here.

like image 20
Henk Holterman Avatar answered Oct 07 '22 17:10

Henk Holterman