Reputation: 23
I have referred to some sites online and It has made me curious about this function. One site recommended the use of assert as function precondition where it could be used for detecting problems related to manipulation of data during parallel threads. But as people say that assert should be removed during release of the software. But we can detect this problems with a simple if else and exit combo. So I dont get how using assert is any different.
Upvotes: 0
Views: 103
Reputation: 3973
In the end it comes down to there being two (or more) kinds of "errors" that you can encounter in your program:
If you have a text field and ask a user to input a date in "yyyy-mm-dd" format, and the user writes "It is tuesday". Then that is a type of error that you can catch and respond to - and moreover, it is not something that is wrong with the program.
On the other hand, if you have a date picker (displays a calendar and lets the user pick there), then it should only be able to return valid dates (and possibly a "user refused to pick" value). If it can return "2020-14-52", then the date picker code is just broken.
If you are concerned that your date picker may be bugged (maybe you are in the process of writing your own), then you can add some assert(validDate(date))
calls to all the date returns you get from your picker. That way the program will terminate with a big red finger pointing at the failed assert every time the date picker returns an invalid date. This is very valuable during development.
However, once you are satisfied that your date picker is working and only returns valid dates, then all those extra checks are redundant and can be removed. But here the assert
has another nice feature; if you compile in debug mode then the check stays, but if you compile in release mode then it becomes an empty call that can be optimized out by the compiler.
In short: Error handling is for stuff that can go wrong during execution in a correctly working program. Asserts are for stuff that must not be able to go wrong (and if it does then something is fundamentally broken in the code).
Upvotes: 1