A Switch-Case versus Polymorphism scenario

M

Myster Ious

Polymorphism replaces switch statements, making the code more
compact/readable/maintainable/OO whatever, fine!

What I understand, that needs to be done at the programming level, is
this:

a switch-case has a variable (most probably an enumeration) &
associated symbols or integral value. Selection is made, base on what
symbol/value the variable holds. So

variable = VALUE1; // selection 1
....
variable = VALUE2; // selection 2
....
switch (variable) {
case VALUE1: DoForValue1(); break;
case VALUE2: DoForValue2(); break;
}

to replace it w polymorphism, the variable substitue is pointerToBase
& symbol/value substitute is 'an instantiation of DerivedClass', e.g.,

pointerToBase = new DerivedClass1; // selection 1
....
pointerToBase = new DerivedClass2; // selection 2
....
pointerToBase->DoAccordingToDerivedClass(); // virtual-call! switch
not needed

Lets look at it with another perspective, i.e., the source of that
selection! Two questions:

1 - If the selection-source is some set of radio-buttons & User
selects & reselects different radios multiple times, the "switch
scenario" doesn't get much effected, but for "polymorph. scenario" we
have to new & delete the various derived classes that much time, it's
like playing with memory (pretty bad particularly if Derived Objects
take-up large memory). Is there any decent substitute?

2 - We can easily persist the variable value in the "switch scenario",
load it again & apply another switch. For "polymorph. scenario",
persisting is easy, call pointerToBase->PersistAccToDerivedClass();
but for loading we have to apply a 'switch statement' because the
persisted object would be just a character-string or integral value
identifying different derivedObjects, how to avoid a switch statement
at this time?
 
D

David White

Myster Ious said:
Polymorphism replaces switch statements, making the code more
compact/readable/maintainable/OO whatever, fine!

I suppose you can express polymorphism in terms of switch statements, but
that doesn't mean you should replace all your switch statements with a
virtual call.
What I understand, that needs to be done at the programming level, is
this:

a switch-case has a variable (most probably an enumeration) &
associated symbols or integral value. Selection is made, base on what
symbol/value the variable holds. So

variable = VALUE1; // selection 1
...
variable = VALUE2; // selection 2
...
switch (variable) {
case VALUE1: DoForValue1(); break;
case VALUE2: DoForValue2(); break;
}

to replace it w polymorphism, the variable substitue is pointerToBase
& symbol/value substitute is 'an instantiation of DerivedClass', e.g.,

pointerToBase = new DerivedClass1; // selection 1
...
pointerToBase = new DerivedClass2; // selection 2
...
pointerToBase->DoAccordingToDerivedClass(); // virtual-call! switch
not needed

Lets look at it with another perspective, i.e., the source of that
selection! Two questions:

1 - If the selection-source is some set of radio-buttons & User
selects & reselects different radios multiple times, the "switch
scenario" doesn't get much effected, but for "polymorph. scenario" we
have to new & delete the various derived classes that much time, it's
like playing with memory (pretty bad particularly if Derived Objects
take-up large memory). Is there any decent substitute?

Yes, the original switch is perfect.
2 - We can easily persist the variable value in the "switch scenario",
load it again & apply another switch. For "polymorph. scenario",
persisting is easy, call pointerToBase->PersistAccToDerivedClass();
but for loading we have to apply a 'switch statement' because the
persisted object would be just a character-string or integral value
identifying different derivedObjects, how to avoid a switch statement
at this time?

I don't know. How about a map of strings and function pointers? How about an
array of function pointers? (for the integral value case) There are no doubt
all sorts of methods. You might even find that a switch does an excellent
job.

Is this a homework question or are you just musing?

DW
 
P

Phlip

David said:
I suppose you can express polymorphism in terms of switch statements, but
that doesn't mean you should replace all your switch statements with a
virtual call.

Only the ones that simplify as they add flexibility.
Is this a homework question or are you just musing?

It's a FAQ because of the learning path. To explain polymorphism, we must
explain how it's interchangable with its opposite. Then the learner goes and
tries to find the situations where it doesn't work. Learners are not often
familiar with the internal engines of programs, where the paradigm
simplifies, but they are often familiar with boundary situations such as
GUIs with fixed constants.
 
K

Kevin Goodsell

Myster said:
Polymorphism replaces switch statements, making the code more
compact/readable/maintainable/OO whatever, fine!

The purpose of polymorphism is *not* to replace "switch" statements.
Your entire post is based on a faulty assumption. I suggest you study
object-oriented design a bit more.

Polymorphism can be accomplished with switch statements and run-time
type information, but such an arrangement is incredibly messy, much more
difficult to maintain, and probably less efficient.
What I understand, that needs to be done at the programming level, is
this:

a switch-case has a variable (most probably an enumeration) &
associated symbols or integral value. Selection is made, base on what
symbol/value the variable holds. So

variable = VALUE1; // selection 1
...
variable = VALUE2; // selection 2
...
switch (variable) {
case VALUE1: DoForValue1(); break;
case VALUE2: DoForValue2(); break;
}

to replace it w polymorphism, the variable substitute is pointerToBase
& symbol/value substitute is 'an instantiation of DerivedClass', e.g.,

pointerToBase = new DerivedClass1; // selection 1
...
pointerToBase = new DerivedClass2; // selection 2

If you didn't bother to delete pointerToBase, then you have a memory
leak here.
...
pointerToBase->DoAccordingToDerivedClass(); // virtual-call! switch
not needed

Lets look at it with another perspective, i.e., the source of that
selection! Two questions:

1 - If the selection-source is some set of radio-buttons & User
selects & reselects different radios multiple times, the "switch
scenario" doesn't get much effected, but for "polymorph. scenario" we
have to new & delete the various derived classes that much time, it's
like playing with memory (pretty bad particularly if Derived Objects
take-up large memory). Is there any decent substitute?

I have a hard time believing any competent programmer would write code
this way. A more likely way would be for the state of the radio button
set to be examined once it's time to take some action based on it, e.g.
when the user clicks the "OK" button. Even then, the action taken
doesn't have to be allocating a polymorphic object. A selection
statement based on the state of the buttons may be much more appropriate.
2 - We can easily persist the variable value in the "switch scenario",
load it again & apply another switch. For "polymorph. scenario",
persisting is easy, call pointerToBase->PersistAccToDerivedClass();
but for loading we have to apply a 'switch statement' because the
persisted object would be just a character-string or integral value
identifying different derivedObjects, how to avoid a switch statement
at this time?

It's far more common to have a set of polymorphic objects and apply some
virtual function to each object in the set in turn. This idea you seem
to have of "allocate, use, throw away, and repeat" is very odd, and
would probably reflect a poor design.

-Kevin
 
D

David White

Phlip said:
It's a FAQ because of the learning path. To explain polymorphism, we must
explain how it's interchangable with its opposite. Then the learner goes and
tries to find the situations where it doesn't work. Learners are not often
familiar with the internal engines of programs, where the paradigm
simplifies, but they are often familiar with boundary situations such as
GUIs with fixed constants.

Well, it's an interesting way to look at it but I question its usefulness.
Stroustrup's C-front was a C++ compiler that output C code, so he had to
implement virtual functions in C. I don't know how he did it but I'm sure he
could have done it with switches if he'd wanted. I think of polymorphism, at
least in its OO definition, in a completely different way. I think of it as
objects of different classes responding differently, but appropriately, to
the same message. I don't see any point in thinking of it as a mechanism to
replace switches. Switches are just a means of implementation.

DW
 
H

H. S. Lahman

Responding to Ious...
Polymorphism replaces switch statements, making the code more
compact/readable/maintainable/OO whatever, fine!

Apples and oranges. Polymorphism is a concept related to transparent
substitution, of which there are several forms. A switch statement is a
3GL implementation that /may/ be used to implement a particular form of
polymorphism (parametric). But the switch statement can also be used
where there is no substitutability (i.e., anyplace where encapsulated
rules and policies could be expressed through cascaded IFs).

The key to parametric polymorphism is that the behavior is substitutable
based upon a specific value(s) of input (message parameters or
attributes). If the values are provided externally, then the object
behavior is substituted with respect to the client. So if the
substitution is based on exactly one such value, a switch can be
conveniently used to implement that substitution.

In contrast, if the substitution is based on values that the object
itself provides (i.e., its knowledge responsibilities), then any
conditions are simply part of the encapsulated rules and policies of the
object itself. It may also be convenient to use a switch in that
context as well.


*************
There is nothing wrong with me that could
not be cured by a capful of Drano.

H. S. Lahman
(e-mail address removed)
Pathfinder Solutions -- We Make UML Work
http://www.pathfindersol.com
(888)-OOA-PATH
 
P

Phlip

It's a FAQ because of the learning path. To explain polymorphism, we must
Well, it's an interesting way to look at it but I question its usefulness.
Stroustrup's C-front was a C++ compiler that output C code, so he had to
implement virtual functions in C. I don't know how he did it but I'm sure he
could have done it with switches if he'd wanted. I think of polymorphism, at
least in its OO definition, in a completely different way. I think of it as
objects of different classes responding differently, but appropriately, to
the same message. I don't see any point in thinking of it as a mechanism to
replace switches. Switches are just a means of implementation.

The explanation is not supposed to be normative. It's just a way to
help a newbie realize, "Oh, I see. When you send a message to an
object, and it selects a method based on the object's type. That's
just like a switch statement with a list of cases, except each case is
written with its object's class, instead of inline after the switch."

You are thinking too hard.
 
U

Universe

David said:
.... I think of polymorphism, at
least in its OO definition, in a completely different way. I think of it as
objects of different classes responding differently, but appropriately, to
the same message. I don't see any point in thinking of it as a mechanism to
replace switches. Switches are just a means of implementation.

Amen!

The Logical should generally lead the way.

Much more flexibility is available in all areas.

Elliott
--
OO software rests upon class abstractions expressed in class method
*behaviors*. The sum of class method behaviors is the overall class
*role*. Class role should have primary responsibility for managing class
data such that the impact of class data is driven by the operation of
class methods.
~*~ Get with OO fundamentals, get OO. ~*~
-
We Don't Need US Fat Cat's Geopolitical Hegemony!
People of the World Demand US Stop Now!
-
* http:\\www.radix.net/~universe *
@Elliott 2003 my comments ~ newsgroups+bitnet OK
 
D

David White

Phlip said:
The explanation is not supposed to be normative. It's just a way to
help a newbie realize, "Oh, I see. When you send a message to an
object, and it selects a method based on the object's type. That's
just like a switch statement with a list of cases, except each case is
written with its object's class, instead of inline after the switch."

You are thinking too hard.

Okay. I had a feeling I was missing something.

DW
 
U

Uncle Bob (Robert C. Martin)

David White said:
Well, it's an interesting way to look at it but I question its usefulness.
Stroustrup's C-front was a C++ compiler that output C code, so he had to
implement virtual functions in C. I don't know how he did it but I'm sure he
could have done it with switches if he'd wanted.

In fact, if you wrote C code based on switch statements and C++ code
based upon virtual functions, there is a chance that you wouldn't be
able to tell the difference by looking at the binary. Both use jump
tables as the means of selection.

I think of polymorphism, at
least in its OO definition, in a completely different way. I think of it as
objects of different classes responding differently, but appropriately, to
the same message.

Yes, this is good to keep in mind. But...
I don't see any point in thinking of it as a mechanism to
replace switches.

You'd think differently if you were faced with re-writing a
switch/case maze. It's always a good idea to remember that
polymorphism can be used to eliminate switch statements.


Robert C. Martin | "Uncle Bob"
Object Mentor Inc.| unclebob @ objectmentor . com
PO Box 5757 | Tel: (800) 338-6716
565 Lakeview Pkwy | Fax: (847) 573-1658 | www.objectmentor.com
Suite 135 | | www.XProgramming.com
Vernon Hills, IL, | Training and Mentoring | www.junit.org
60061 | OO, XP, Java, C++, Python |
 
M

Myster Ious

Uncle Bob (Robert C. Martin) said:
1 - If the selection-source is some set of radio-buttons & User
selects & reselects different radios multiple times, the "switch
scenario" doesn't get much effected, but for "polymorph. scenario" we
have to new & delete the various derived classes that much time, it's
like playing with memory (pretty bad particularly if Derived Objects
take-up large memory). Is there any decent substitute?]
Yes.
a. Don't 'new' and 'delete' them. Keep static instances and swap
pointers.
b. Keep a variable that corresponds to the radiobutton and then, once
the OK button has been clicked, use a switch statement (or better yet
an array index) to create the appropriate object. My rule about
switch statements is that they are OK so long as they are creating
derivatives that will be used elsewhere to eliminate many other switch
statements.
2 - We can easily persist the variable value in the "switch scenario",
load it again & apply another switch. For "polymorph. scenario",
persisting is easy, call pointerToBase->PersistAccToDerivedClass();
but for loading we have to apply a 'switch statement' because the
persisted object would be just a character-string or integral value
identifying different derivedObjects, how to avoid a switch statement
at this time?
Lots of people use symbol tables or hashmaps instead of switch
statements, but logically they turn out to be the same thing. Once
again I apply my rule. A switch statement can be used to create an
derivative.

Thank you all for suggestions, especially 'Uncle Bob', I think my case
is closest to the solution Uncle Bob presented. Its better to have 2
switch'es/symbol-tables (one after radio selection & one after
loading a persisted value) than have dozens of switches through-out
the code.

My first statement raised a lot of critism, which claimed that
'Polymorphism is not a replacement for every switch scenario'. Perhaps
I couldn't explain well, actually I was talking about only that
'switch scenario' that can & should be replaced by 'polymorphism' but
one that presents minute obstacles in allowing the programmer to do
so.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top