Is assert evil? [closed]
The Go
language creators write:
Go doesn't provide assertions. They are undeniably convenient, but our experience has been that programmers use them as a crutch to avoid thinking about proper error handling and reporting. Proper error handling means that servers continue operation after non-fatal errors instead of crashing. Proper error reporting means that errors are direct and to the point, saving the programmer from interpreting a large crash trace. Precise errors are particularly important when the programmer seeing the errors is not familiar with the code.
What is your opinion about this?
Solution 1:
No, there's nothing wrong with assert
as long as you use it as intended.
That is, it's supposed to be for catching cases that "can't happen", during debugging, as opposed to normal error handling.
- Assert: A failure in the program's logic itself.
- Error Handling: An erroneous input or system state not due to a bug in the program.
Solution 2:
No, neither goto
nor assert
are evil. But both can be misused.
Assert is for sanity checks. Things that should kill the program if they are not correct. Not for validation or as a replacement for error handling.
Solution 3:
By that logic, breakpoints are evil too.
Asserts should be used as a debugging aid, and nothing else. "Evil" is when you try using them instead of error handling.
Asserts are there to help you, the programmer, detect and fix problems that must not exist and verify that your assumptions stay true.
They have nothing to do with error handling, but unfortunately, some programmers abuse them as such, and then declare them "evil".
Solution 4:
I like to use assert a lot. I find it very useful when I am building applications for the first time (perhaps for a new domain). Instead of doing very fancy error checking (that I would consider premature optimization) I code fast and I add a lot of asserts. After I know more about how things work I do a rewrite and remove some of the asserts and change them for better error handling.
Because of asserts I spend a lot of less time coding/debugging programs.
I've also noticed that the asserts help me think of many things that could break my programs.