PyWart: More surpises via "implict conversion to boolean" (and other steaming piles!)
Tim Chase
python.list at tim.thechases.com
Thu Feb 13 06:39:52 EST 2014
On 2014-02-13 04:11, Steven D'Aprano wrote:
> give_me_an_even_number()
> => returns 42
> give_me_an_even_number()
> => returns 23
>
> Hmmm. There's a bug in give_me_an_even_number(). How do I reproduce
> that bug? What arguments do I pass? Oh, the same no-arguments as
> for the working call.
>
> Clearly, the function must have *hidden state*. Hidden state (e.g.
> a global variable) makes it hard to reason about the function call,
> since you don't know what the hidden state is. So that's also a bit
> smelly.
I'd even go so far as to claim that this is the primary reason a
zero-argument function is a code-smell. Not because zero-argument
functions smell, but because hidden-state smells and zero-argument
functions imply hidden-state. Date/time functions are a personal pet
peeve for just this reason, and require addressing the hidden-state
of the system clock regardless of parameter-count. Thus instead of
something like
class Person:
def __init__(self, name, dob):
self.name = name
self.dob = dob
def age(self):
return datetime.date.today() - self.dob
I do
def age(self, as_of=None):
if as_of is None:
as_of = datetime.date.today()
return as_of = self.dob
allowing me to test the function with known dates.
> > There are code smells that are the opposite in fact, methods with
> > long parameter lists are generally seen as code smell (“passing a
> > paragraph”).
>
> Absolutely! You'll get no disagreement from me there.
*coughtkintercough*
-tkc
More information about the Python-list
mailing list