Where to put the error handing test?

Peng Yu pengyu.ut at gmail.com
Tue Nov 24 10:47:58 EST 2009


On Tue, Nov 24, 2009 at 12:27 AM, alex23 <wuwei23 at gmail.com> wrote:
> On Nov 24, 1:15 pm, Peng Yu <pengyu... at gmail.com> 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.
>>
>> 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().
>
> What you should try to do is make each function as self-contained as
> possible. f() shouldn't have to know what is a valid argument for g(),
> that's the responsibility of g(). What f() needs to know is how to
> deal with any problems that arise while using g().

This may not always be possible, because g() might call a third party
software, that I don't have the complete knowledge of. What would you
do if this case?

Another scenario:

Suppose that f_1(),...,f_<n>(), g() are in a package, where g() is an
internal function that the end users are not suppose to call, and
f_1(),...,f_<n>() are the functions that the end users may call.

Since all the f_1 ... f_<n> functions knows g(), they can be
programmed to guarantee not to pass any arguments that can not be
handled by g(). In this case, I think it is reasonable to move the
test code from g()? Is it the general accepted practice?

> As a very rough example:
>
>    def g(x):
>        try:
>            assert isinstance(x, int)
>        except AssertionError:
>            raise TypeError, "excepted int, got %s" % type(x)
>        # ... function code goes here
>
>    def f(x):
>        try:
>            g(x)
>        except TypeError:
>            # handle the problem here
>        # ... function code goes here
>
>> 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().
>
> This sounds strange to me. Are you stating that h() can pass values to
> g() that would be illegal for f() to pass? That sounds like a very
> dangerous design...you want each function's behaviour to be as
> consistent and predictable as it possibly can.

You misunderstood me.

h() doesn't pass any illegal arguments to g(). If I put the test code
in g(), it would be a waste of run time when h() calls g(). In this
case, and under the condition that g() is an internal function of a
package as I mentioned above, I think I should move the test code from
g() to f(). What do you think?



More information about the Python-list mailing list