Where to put the error handing test?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue Nov 24 03:11:24 EST 2009


alex23 a écrit :
> 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(). 

There's no such clear-cut IMHO - it really depends on the context. If f 
is a user-interface function - a function that deals with user inputs in 
whatever form - and g is a domain-specific library function, then it's 
f's responsability to validate user inputs before calling on g (_and_ of 
course to deal with any exception raised withing g).

As a general rule, "defensive code" should go at the interface level - 
program's inputs of course, but also, sometimes, at "sub-systems" 
boundaries.



More information about the Python-list mailing list