473,397 Members | 2,099 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

A Switch-Case versus Polymorphism scenario

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?
Jul 19 '05 #1
10 10867
Myster Ious <yo*****************@yahoo.com> wrote in message
news:5d**************************@posting.google.c om...
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

Jul 19 '05 #2
David White wrote:
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.

--
Phlip
http://clublet.com/c/c/why?ZenoBuddhism
-- Ask about our Venture Capital
ignition outsourcing services --
Jul 19 '05 #3
Myster Ious wrote:
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

Jul 19 '05 #4
Phlip <ph*******@yahoo.com> wrote in message
news:r3*************@newssvr16.news.prodigy.com...
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

Jul 19 '05 #5
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
hs*@pathfindersol.com
Pathfinder Solutions -- We Make UML Work
http://www.pathfindersol.com
(888)-OOA-PATH


Jul 19 '05 #6
> > 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.


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.

--
Phlip
http://www.c2.com/cgi/wiki?PhlIp
-- Personally qualified to snub Mensa --
Jul 19 '05 #7
David White wrote:
.... 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
Jul 19 '05 #8
Phlip <ph*******@yahoo.com> wrote in message
news:63*************************@posting.google.co m...
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

Jul 19 '05 #9
"David White" <no@email.provided> might (or might not) have written
this on (or about) Thu, 31 Jul 2003 16:42:20 +1000, :

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 |
Jul 19 '05 #10
"Uncle Bob (Robert C. Martin)" <u.*************@objectmentor.com> wrote in message news:<kr********************************@4ax.com>. ..
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.
Jul 19 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Rudi Hansen | last post by:
I dont seem to be able to find the switch statement in Python. I would like to be able to do switch(var) case 1 : print "var = 1" case 2: print "var = 2"
5
by: Bryan Parkoff | last post by:
C++ programmers and I tried to experience by writing 65536 switch cases. It is too large for Windows XP and other operating system to handle. It looks like that JMP Table obtains 256K bytes for...
2
by: jr | last post by:
I have a niggle with the Switch function I have a querey which has a column with 3 digit values of which there are about 20 which are unique. These are meaningless to the user and so using...
13
by: webzila | last post by:
Hello, I have to write a program for an 8051 micro-controller using micro-C to monitor Switch 1 and if the switch in pushed the message "switch 1 pushed" should be displayed in the LCD. Also the...
12
by: junky_fellow | last post by:
Which is better using a switch statement or the if-then equivalent of switch ?
65
by: He Shiming | last post by:
Hi, I just wrote a function that has over 200 "cases" wrapped in a "switch" statement. I'm wondering if there are performance issues in such implementation. Do I need to optimize it some way? ...
13
by: William Stacey | last post by:
Using the following code sample: public byte Get() { // <= Possible to switch Here?? lock(syncLock) { //Do something in Get(). } }
5
by: Nadav | last post by:
Hi, I am using FileStream's Async API: BeginRead/EndRead, upon completion callback execution I use the read data and call EndRead, Taking that in mind, I Wonder... does calling EndRead will cause...
13
by: Michael Griebe | last post by:
Simple question. I am optimizing some C++ code and I'd like to know which is faster (or if there is any difference at all) between using a switch statement or nested else-ifs. I'm partial to...
11
by: Peter Kirk | last post by:
Hi i have a string variable which can take one of a set of many values. Depending on the value I need to take different (but related) actions. So I have a big if/else-if construct - but what is...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.