Where to put the error handing test?

Peng Yu pengyu.ut at gmail.com
Mon Nov 23 23:08:39 EST 2009


On Mon, Nov 23, 2009 at 9:44 PM, Lie Ryan <lie.1296 at gmail.com> wrote:
> Peng Yu wrote:
>>
>> Suppose that I have function f() that calls g(), I can put a test on
>> the argument 'x' in either g() or f(). I'm wondering what is the
>> common practice.
>>
>> My thought is that if I put the test in g(x), the code of g(x) is
>> safer, but the test is not necessary when g() is called by h().
>>
>> If I put the test in f(), then g() becomes more efficient when other
>> code call g() and guarantee x will pass the test even though the test
>> code in not in g(). But there might be some caller of g() that pass an
>> 'x' that might not pass the test, if there were the test in g().
>
> Typically, you test for x as early as possible, e.g. just after user input
> (or file or url load or whatever). After that test, you can (or should be
> able to) assume that all function calls will always be called with the
> correct argument. This is the ideal situation, it's not always easy to do.
>
> In any case though, don't optimize early.

Let's suppose that g() is refactored out from f() and is call by not
only f() but other functions, and g() is likely to be called by new
functions.

If I don't optimize early, I should put the test in g(), rather than f(), right?



More information about the Python-list mailing list