Where to put the error handing test?
lie.1296 at gmail.com
Tue Nov 24 04:44:16 CET 2009
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.
More information about the Python-list