The content of this blog is my personal opinion only. Although I am an employee - currently of Imagination Technologies's MIPS group, in the past of other companies such as Intellectual Ventures, Intel, AMD, Motorola, and Gould - I reveal this only so that the reader may account for any possible bias I may have towards my employer's products. The statements I make here in no way represent my employer's position, nor am I authorized to speak on behalf of my employer. In fact, this posting may not even represent my personal opinion, since occasionally I play devil's advocate.

See http://docs.google.com/View?id=dcxddbtr_23cg5thdfj for photo credits.

Thursday, June 02, 2016

Should asserts be disabled in production?

I used to be quite annoyed by Perl CPAN's

Carp::Assert: "assert(...) if DEBUG;"
i.e. by the fact that you have to append "if DEBUG" to an assertion in order to get it disabled in production.

Now, I have flipped.

I often want assertions enabled in production code. At least cheap assertions.  In fact, I might go so far as to say "assertions should be enabled in production code by default, unless you explicitly say not to".

In which case, the Perl Carp::Assert syntax is not totally unreasonable.

I might prefer the Pythonish

if DEBUG: assert(...)

so that you can see the "if DEBUG" right up front.

But then again, Python's assert is disabled when you run Python "optimized" via python -O.

I was somewhat flabbergasted when I encountered Python style guides that recommended not using asserts, or specifically not using asserts inside library functions.    (Can't find a reference right now, so perhaps this is rare advice.)

Reason: since Python assert is disabled when you run optimized -O (which is common in some worlds), and since libraries cannot be sure that somebody competent is calling them, libraries should do

if !valid(parameter): raise someException
rather than

assert valid(parameter)
This advice is accurate, but unfortunate.  I always prefer concise code, and "assert" is more concise than "if...raise".   And probably less fragile, since exception hierarchies have a habit of changing.

So I can't blame Python, but I can still regret it.

No comments: