Ask Forgiveness Not Permission

This is a programming notion rather than the recipe for a long and happy marriage!

As I’ve been reading, I’m been coming across many references to the pythonic principle of Ask Forgiveness Not Permission.

It’s not difficult. You probably know it. You just didn’t know it had that name.

An example of asking permission would be:

if (i_can_do_it):

vs the ask forgiveness approach of:

except (i_cant_do_it):

There are a couple of main reasons behind the practice.

Firstly, in any concurrent system there is the potential for there to be a race condition between the evaluation of i_can_do_it and the action of do_it (see more from db code example below).

Secondly, the comprehensive list of things you need to check for permission may be lengthy and/or not be possible to either know or cover in their entirety so you end up having to cover the exceptions anyway.

So, going back to my roots, you often see this pattern in PLSQL and SQL with a SELECT check followed by a subsequent action if something exists:

      select ... from ....
      do something;
    when no_data_found then
         do something else

Apart from anything else, another session may have inserted or deleted a row in between the time in which you did the select and you then attempting the subsequent do_something.

Better to attempt the do_something and then react to the no_data_found exception or react to the attributes of SQL%ROWCOUNT/FOUND/NOTFOUND.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s