Recommendations (or best practices) to define functions (or methods)

Frank Millman frank at chagford.com
Tue Jan 9 08:14:54 CET 2007


Diez B. Roggisch wrote:
>
> If you don't handle the exceptions, exactly what you seem to want will
> happen - you will see the interpreter stop, and why.
>
> All you did was to take the unpythonic (and un-javaic and un-C#ic) road
> to transform an exception to a returncode. But that has nothing to do
> with actually _dealing_ with the error. Instead, it just makes it more
> likely that you _don't_ deal with it, as a return-code evaluation might
> be more easily forgotten, and turn out with a program that will be
> error-prone, as it continues to run even when the preconditions for
> pieces of code aren't met anymore.
>

I absolutely agree with this. I will describe my particular experience,
in the hope that it will make it clear to vizcayno just how important
this is.

My app does a lot of database/user interaction. I read a row from the
database, display it to the user, allow the user to change the value of
various columns, and write it back again.

I had a routine which validated whether the user input was acceptable
based on various business rules. If the input was good, it would update
the internal value of the column and return True, else it would not
update the value and return False. I would check the return code and,
if False, display an error message and reprompt the user for input.
What could go wrong with that?

Well, during the execution of the program, I also update the values of
various columns programatically. I call the same routine, but I did not
check the return code, as it would add a lot of extra checks, and as it
was program generated it would always pass a valid value.

This was true 99.9% of the time, but occasionally, due to a program
error, I would pass an invalid value. The validation routine correctly
did not update the internal value, and returned False, but as I did not
check this I continued merrily on my way. Later on when I found that
the value had not changed, it took me a long time to trace the error.

I suffered like this for quite a long time before the light bulb went
off, based on a thread on c.l.py. Now I do it like this.

The validation routine performs the same function, but instead of
returning True/False, it raises ValueError if the check fails. Where I
previously tested the return code, I now have a try/except clause,
which does the same as before.

The big difference is, what happens if I programmatically pass an
invalid value? Where before, the error would pass silently, now my
program aborts, with the traceback, which is exactly what I want.

Frank Millman




More information about the Python-list mailing list