On 04/01/14 20:11, Alex Kleider wrote:

Assuming I am correct that in Python, switch statements must be
implemented as a series of if; elif; .. statements, how is it that this
can be avoided by creating subclasses?


Its called polymorphism and is one of the most powerful advantages of OOP since case or switch statements are one of the most fault prone structures in procedural programming.

You can see an example in my OOP topic in my tutor under the heading
'Same thing, Differenmt thing'

http://www.alan-g.me.uk/tutor/tutclass.htm

It uses a Shape class and several subclasses - Square, Triangle, Circle.
It calculates the areas of a list of these shapes.

Without OOP you would need to do something like

for shape in shapes:
    if shape['type'] == CIRCLE:
        result = circle_area(shape['radius'])
    elif shape['type'] == SQUARE:
        result = square_area(shape['length'])
    elif ....

But with OOP we simply call each shapes area method and
the interpreter works out which method to call:

for shape in shapes:
 result = shape.area()

This has several benefits.

First we can add new shape types and not have to change any of the application level code. The new shapes will supply their own area() methods and all is well.

Second if we use the case style and need to modify the set of tests, we probably will need to do this in all sorts of places in our code.
It's easy to forget one statement in a rarely used backwater...

Thirdly polymorphism means we never inadvertently miss out a case.
OOP will handle all object types in all situations. Cases can only handle the cases they have been programmed for.

Finally the case statement require an intimate knowledge of both the attributes used for the test (if they ever get renamed, ouch!)
and also the calling signatures (including how many and what type
of parameters they have and the names) of the area functions. The OOP area method can use the internal attributes so no arguments need be provided. (The alternative for the switch is that the functions
rely on the incoming object being cast or type converted to
the correct shape subtype, which is almost as unreliable as
reading the correct attributes). Even worse is that for short
functions like area it's often tempting to inline the calculation
within the case block. But then the same calculation is needed
somewhere else and we then get duplicate code to maintain as
well!


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to