Message ID
DKIM signature
Download raw message
Hi Chris,

Nice article as usual ("Assertions should be more debugger-oriented").
I had a thought in response to the following line:

"They’re sometimes abused for error handling, which is a reason
they’ve also been (wrongfully) discouraged at times. For example,
failing to open a file is an error, not a defect, so an assertion is

What about things that are in the grey area, say, the failure of
pthread_mutex_lock? While this could be an error, in my opinion it is
much more likely a defect. Would you advocate against the use of an
assertion in such a case? I typically handle these things as a
programmer error ("assert()") or as a fatal error ("log_and_die()")
depending on mood, but I almost never return an error code in such a
case. Curious for your thoughts.

Message ID
<CAKF5_TmH=vfO6GduhR7Hv+-AtpNPqh3WQ4CXvCcYeimOKsk74Q@mail.gmail.com> (view parent)
DKIM signature
Download raw message
> the failure of pthread_mutex_lock?

That's a great example, Harris. I agree with you: This is an appropriate 
case for an assertion since, as you pointed out, it can only fail as the 
result of programmer error. In other words, it's a defect rather than an 
error condition. On the other hand, asserting pthread_mutex_init success 
is incorrect since it can legitimately fail even in a correct program by 
failing to allocate a resource (e.g out of memory).

Generally I prefer interfaces that, if making the effort to check, abort 
on misuse instead of indicating misuse through an error return. Correct 
programs will be unaffected, and incorrect programs are more likely to be 
noticed. The sort of program that asserts on pthread_mutex_lock is the 
least likely misuse it in the first place.

Similarly, just as one can overuse assertions, applying them to errors, 
one can also underuse them. Frequently when reviewing Go programs I'll 
wonder why a function returns "error" when I cannot imagine any reason why 
it could fail. Digging further, I'll find the author has decided to return 
an error when the function is misused by the programmer, as though a 
message naming parameters might be useful to the program's user. Even the 
Go standard library does this, with various functions in cipher and crypto 
panicking for some cases of misuse but returning errors for other cases.
Reply to thread Export thread (mbox)