It's a bird, it's a plane, it's

Everything here is my opinion. I do not speak for your employer.
July 2015
August 2015

2015-07-28 »

I've been sending the same code review comments to several different people lately, so I thought I might share it.

1) Do not redirect stderr to /dev/null. Trust me, you're gonna want the error message someday.  If your program is producing something stupid on stderr every time it runs, find a safer way to make the stupid message not appear: for example, add a –quiet option or something to ask it to not print useless information.

2) When catching exceptions, make the 'try' section of your try/except or try/catch block as short as possible.  In python:

WRONG
   try:
      maybe_throw_FooError()
      ... do a bunch more stuff ...
   except FooError:
      ...

RIGHT
   try:
     maybe_throw_FooError()
   except FooError
     ...
   else:
     ... do a bunch more stuff ...

(Also acceptable: don't use an 'else' clause at all and just put the rest of the code below the try/except block.  Which is preferable depends on the flow you want, especially whether you do 'pass' inside the except block or not.)

The idea with #2 is that if "do a bunch more stuff" accidentally throws a FooError that you weren't expecting, you don't want to accidentally catch it with your original FooError handler, because a) you're handling a FooError you weren't expecting so you might handle it wrong, and b) you're masking an error condition you didn't know existed.  Better to let the exception leak out and get a useful stack trace.

These things seem obvious to me after years of doing it, but looking back, I guess I had to be taught these things at some point too. Spread the word :)

I'm CEO at Tailscale, where we make network problems disappear.

Why would you follow me on twitter? Use RSS.

apenwarr on gmail.com