[Tutor] Tips
Danny Yoo
dyoo at hashcollision.org
Wed Jun 18 06:11:40 CEST 2014
On Tue, Jun 17, 2014 at 5:02 PM, Alex Kleider <akleider at sonic.net> wrote:
> On 2014-06-17 13:35, Alan Gauld wrote:
>
>> Don't test types, use the interface
>
>
> Can you please explain what you mean by this?
If you are writing type tests on a function's inputs, you might better
off by having the inputs implement an interface: the design of the
program will often be more maintainable.
As a toy example, consider the following:
###################################
class Football(object):
pass
class Baseball(object):
pass
def printBallSize(game):
if isinstance(game, Football):
print "The ball is 68-70cm"
if isinstance(game, Baseball):
print "The ball is 229-235mm"
raise ValueError
###################################
The problem with getBallSize() is that it hardcoded a decision based
on what the type of the input is. It's a bit fragile.
A more flexible design allows the game itself to provide that
information for itself:
###################################
class Football(object):
def size(self):
return "68-70cm"
class Baseball(object):
def size(self):
return "229-235mm"
def printBallSize(game):
return "The ball is", game.size()
###################################
The reason the latter is usually preferable is because additional
games can be supported without having to revise printBallSize(). For
example, we can write:
###################################
class AmericanFootball(object):
def size(self):
return "68-70cm"
###################################
and printBallSize() will work on American footballs as well.
printBallSize() works on anything that implements a size() method.
The example above is very toy. A more realistic example might be
writing a function whose inputs might be assumed to be a sequence.
Rather than hardcode a test that explicitly checks whether the input
is a list, just use it. Then anything that satisfies the
"interface"---the way you're using the input---will often Just Work.
Tuples, for example, will do many of the things that lists will do.
And in some cases, even a file might look like a list, for all
practical purposes, if all we care about is iterating though it once.
Hope that makes some sense!
More information about the Tutor
mailing list