Function "modes" vs. separate functions

Ben Finney ben+python at
Fri Jul 29 21:57:34 EDT 2011

Andrew Berg <bahamutzero8825 at> writes:

> On 2011.07.29 07:50 PM, Steven D'Aprano wrote:
> > Especially if the implementation looks like this:
> > 
> > def get_thing(argument, flag):
> >     if flag:
> >         return one_thing(argument)
> >     else:
> >         return another_thing(argument)
> > 
> Well, that would be annoying, but wouldn't it be even more annoying to
> do this:
> def get_one_thing(arg):
> 	return one_thing(arg)
> def get_another_thing(arg):
> 	return another_thing(arg)

Yes, of course it would be; and even more pointless.

The right thing to do is to call ‘one_thing(argument)’ or
‘another_thing(argument)’ directly.

The greater point is that, since the flag simply switches between
different “things” to do, then that's better communicated in code by
calling differently-named functions that each do one thing.

> Creating separate functions for two thing that do almost the same
> thing seem more of a nuisance to me, especially if they share a lot of
> code that isn't easily separated into other functions.

If they share a lot of code, either it *is* separable to common
functions (in which case, implement it that way), or the “same thing”
code is sufficiently complex that it's better to show it explicitly.

But this is all getting rather generic and abstract. What specific
real-world examples do you have in mind?

 \          “It is clear that thought is not free if the profession of |
  `\           certain opinions makes it impossible to earn a living.” |
_o__)  —Bertrand Russell, _Free Thought and Official Propaganda_, 1928 |
Ben Finney

More information about the Python-list mailing list