473,383 Members | 1,846 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,383 software developers and data experts.

Calling Method From Switch{}

Is it fine to call another method from Switch?

Eg.

Switch (stringVar)
{
case ("a"):
somVar = "whatever";
Another_Method(); //call another method
return;
case ("g"):
somVar = "somethingelse";
Another_Method_2(); //call another method
return;
}

Is this a recommended approach or should it just be an if statement?

Dec 10 '06 #1
12 12212
msnews.microsoft.com wrote:
Is it fine to call another method from Switch?

Eg.

Switch (stringVar)
{
case ("a"):
somVar = "whatever";
Another_Method(); //call another method
return;
case ("g"):
somVar = "somethingelse";
Another_Method_2(); //call another method
return;
}

Is this a recommended approach or should it just be an if statement?
It's fine. Personally I find a switch statement preferable any time the
alternatives depend on the same source data . You could write the above as:

if (stringVar="a")
{
// ...
}
else if (stringVar="g")
{
// ...
}

....but I wouldn't. The structure of the code is clearer using the switch
than using stacked if statements testing the same variable.

-cd
Dec 10 '06 #2
Carl Daniel [VC++ MVP] wrote:
It's fine. Personally I find a switch statement preferable any time the
alternatives depend on the same source data . You could write the above as:

if (stringVar="a")
{
// ...
}
else if (stringVar="g")
{
// ...
}

...but I wouldn't. The structure of the code is clearer using the switch
than using stacked if statements testing the same variable.
==

Arne
Dec 10 '06 #3
While not syntactically or semantically incorrect, clearly use of a switch to
invoke methods isn't object-oriented. You should consider using inheritance
and polymorphism instead.

--
Browse http://connect.microsoft.com/VisualStudio/feedback/ and vote.
http://www.peterRitchie.com/blog/
Microsoft MVP, Visual Developer - Visual C#
"msnews.microsoft.com" wrote:
Is it fine to call another method from Switch?

Eg.

Switch (stringVar)
{
case ("a"):
somVar = "whatever";
Another_Method(); //call another method
return;
case ("g"):
somVar = "somethingelse";
Another_Method_2(); //call another method
return;
}

Is this a recommended approach or should it just be an if statement?

Dec 10 '06 #4
Hi Peter,

While I agree that an OO solution is usually better in general and so should
always be considered, I don't see how the use of a switch statement
automatically implies a poor design. For instance, switching on a string
argument passed to a console application's Main method or switching on
string input entered into a TextBox sounds perfectly reasonable to me if a
switch statement is the only thing required to perform the operation. As
soon as it becomes switches in combination with ifs and gotos, I'd start to
worry :)

--
Dave Sexton

"Peter Ritchie [C# MVP]" <PR****@newsgroups.nospamwrote in message
news:39**********************************@microsof t.com...
While not syntactically or semantically incorrect, clearly use of a switch
to
invoke methods isn't object-oriented. You should consider using
inheritance
and polymorphism instead.

--
Browse http://connect.microsoft.com/VisualStudio/feedback/ and vote.
http://www.peterRitchie.com/blog/
Microsoft MVP, Visual Developer - Visual C#
"msnews.microsoft.com" wrote:
>Is it fine to call another method from Switch?

Eg.

Switch (stringVar)
{
case ("a"):
somVar = "whatever";
Another_Method(); //call another method
return;
case ("g"):
somVar = "somethingelse";
Another_Method_2(); //call another method
return;
}

Is this a recommended approach or should it just be an if statement?


Dec 10 '06 #5
I only said it wasn't object-oriented. It would depend on whether your view
of deviating from object-orientation results in poor design. But, I should
have clarified by saying that particular switch; but some purists would
consider any switch...

I'm more pragmatic; my view is that following object-orientation strictly
must be weighted against many different aspects, like performance.

Even a set of expected command-line arguments could be used to create an
object of specific type with a common base interface. Although the
implementation would likely result in only displacing the switch statement or
its equivalent; it would also likely optimize the use of the switch to once
instead of many.
--
Browse http://connect.microsoft.com/VisualStudio/feedback/ and vote.
http://www.peterRitchie.com/blog/
Microsoft MVP, Visual Developer - Visual C#
"Dave Sexton" wrote:
Hi Peter,

While I agree that an OO solution is usually better in general and so should
always be considered, I don't see how the use of a switch statement
automatically implies a poor design. For instance, switching on a string
argument passed to a console application's Main method or switching on
string input entered into a TextBox sounds perfectly reasonable to me if a
switch statement is the only thing required to perform the operation. As
soon as it becomes switches in combination with ifs and gotos, I'd start to
worry :)

--
Dave Sexton

"Peter Ritchie [C# MVP]" <PR****@newsgroups.nospamwrote in message
news:39**********************************@microsof t.com...
While not syntactically or semantically incorrect, clearly use of a switch
to
invoke methods isn't object-oriented. You should consider using
inheritance
and polymorphism instead.

--
Browse http://connect.microsoft.com/VisualStudio/feedback/ and vote.
http://www.peterRitchie.com/blog/
Microsoft MVP, Visual Developer - Visual C#
"msnews.microsoft.com" wrote:
Is it fine to call another method from Switch?

Eg.

Switch (stringVar)
{
case ("a"):
somVar = "whatever";
Another_Method(); //call another method
return;
case ("g"):
somVar = "somethingelse";
Another_Method_2(); //call another method
return;
}

Is this a recommended approach or should it just be an if statement?



Dec 11 '06 #6
Hi Peter,
>I only said it wasn't object-oriented. It would depend on whether your
view
of deviating from object-orientation results in poor design. But, I
should
have clarified by saying that particular switch; but some purists would
consider any switch...
I do believe that deviating from an OO design is usually a poor choice, but
if a switch isn't OO to begin with then I see no problem with just keeping
the switch, as long as it's simple like the OP's original code sample. When
I see "switch" I don't automatically think "change is required", especially
when it's perfectly obvious what the code is doing. The OP's code simply
switches on a string for two cases. It sets a (presumably) field's value,
calls a specific method based on the string and returns immediately to the
caller for each of the two cases. It doesn't get much clearer than that,
especially if that code sits in the Main method of a console application or
an event handler for the TextBox.TextChanged event, for example.
I'm more pragmatic; my view is that following object-orientation strictly
must be weighted against many different aspects, like performance.
Agreed.

But the C# switch statement seems to provide optimizations that will
increase performance over "ifs", which are certainly required if an OO
solution is to be used to control flow based on user input or console
arguments. For instance, the strategy pattern may encapsulate each switch
case into an object, however when determining which object to use the string
would still have to be evaluated. An OO design to replace a switch
statement isn't really appropriate unless the operation can be modified from
input string processing to method invocation, which isn't the case with user
input.

I haven't found any conclusive evidence of switch's performance, but there
seems to be quite a lot of information found on newsgroups that state this
claim through testing. For example, here's a recent thread:

http://www.developersdex.com/csharp/...1111&r=5445082

Here's a somewhat older thread:

http://groups.google.com/group/micro...398ce10221171b
Even a set of expected command-line arguments could be used to create an
object of specific type with a common base interface. Although the
implementation would likely result in only displacing the switch statement
or
its equivalent; it would also likely optimize the use of the switch to
once
instead of many.
It's possible, and I'm not suggesting that it shouldn't be considered,
however I think that legibility, performance and ease of management are also
worth consideration and switch may be the better solution at times, such as
in the OP's original sample code. Scalability should also be of concern and
a more OO pattern would help there, but I generally disagree with those
purists that you mentioned above - I really don't think that a simple switch
statement is all that bad and I believe the OP's example is just that.

--
Dave Sexton
Dec 11 '06 #7
Peter Ritchie [C# MVP] wrote:
Although [an OO]
implementation would likely result in only displacing the switch statement or
its equivalent; it would also likely optimize the use of the switch to once
instead of many.
To me, this is a much better argument than an ideological argument
like "switches aren't object oriented." Ideology arouses a So What
reaction in anyone with an ounce of independence, while the appeal of
minimizing duplication is obvious to anyone who's ever had to track
down all the different places that you need to change to add a new
feature or new datatype.

--

..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.
Dec 11 '06 #8
Hi Dave.
I do believe that deviating from an OO design is usually a poor choice, but
if a switch isn't OO to begin with then I see no problem with just keeping
the switch, as long as it's simple like the OP's original code sample.
If the switch statement is only ever evaluated once the choice between
keeping a switch statement or re-redesigning something "more" object oriented
is somewhat moot. I would tend to err on the side of OO in this case; but I
wouldn't fault someone for using a switch. Given the nature of the question
I assumed the switch was being evaluated many times while the value of the
evaluation was constant. Given the choice between performing one if/switch
at object creation then performing multiple lookups into a vtable for a
method and performing an if/switch multiple times, I would choose the
polymorphic route.
When
I see "switch" I don't automatically think "change is required", especially
when it's perfectly obvious what the code is doing.
Agreed. And the example (that looked academic) didn't provide enough
information to accurately make a judgement whether going polymorphic would
offer any performance benefit, hence the "consider". It would be fairly moot
whether "if" or "switch" was more performant in a repetitive situation if you
can avoid repeating the evaluation altogether; but not enough information was
given.
But the C# switch statement seems to provide optimizations that will
increase performance over "ifs", which are certainly required if an OO
solution is to be used to control flow based on user input or console
arguments.
To performance, there's nothing inherent in a switch statement that is any
faster than writing the most optimized set of if statements. Arguably you
could write equally just as performant gotos... Ifs would be more
maintainable than gotos, switches more maintainable than ifs, and, I believe,
polymorphism would be more maintainable to switches.
I haven't found any conclusive evidence of switch's performance, but there
seems to be quite a lot of information found on newsgroups that state this
claim through testing. For example, here's a recent thread:

http://www.developersdex.com/csharp/...1111&r=5445082
Interesting thread, and in fact one suggestion is a dictionary of
delegates--which smells a lot like a vtable to me.
Here's a somewhat older thread:

http://groups.google.com/group/micro...398ce10221171b

It's possible, and I'm not suggesting that it shouldn't be considered,
however I think that legibility, performance and ease of management are also
worth consideration and switch may be the better solution at times, such as
in the OP's original sample code. Scalability should also be of concern and
a more OO pattern would help there, but I generally disagree with those
purists that you mentioned above - I really don't think that a simple switch
statement is all that bad and I believe the OP's example is just that.
I don't think hoisting the switch into a factory and creating objects based
on some value doesn't make it any less legible. Plus, simply adding another
virtual method is all it takes to reuse that evaluation. The switch, as
written in the original example, could only be reused by copy-paste-modify.
A switch statement on its own, of course, isn't bad.
Dec 11 '06 #9
Hi Jon,

I agree that code reuse is certainly a good reason to use OOP instead of
duplicating switch statements, but I believe that concept applies to the
duplication of any statements, not just switches.

It's not obvious to me whether the OP requires duplication, but since there
are certainly situations for a switch statement to appear only once within
the scope of a project, and since it's more common in my experience for a
switch to only be used once, I assume that the OP's requirements are just
the same. If, in fact, the code will be duplicated then I'd certainly agree
that a better design is in order, whether it's a more OO approach or a
simple utility method.

--
Dave Sexton

"Jon Shemitz" <jo*@midnightbeach.comwrote in message
news:45***************@midnightbeach.com...
Peter Ritchie [C# MVP] wrote:
>Although [an OO]
implementation would likely result in only displacing the switch
statement or
its equivalent; it would also likely optimize the use of the switch to
once
instead of many.

To me, this is a much better argument than an ideological argument
like "switches aren't object oriented." Ideology arouses a So What
reaction in anyone with an ounce of independence, while the appeal of
minimizing duplication is obvious to anyone who's ever had to track
down all the different places that you need to change to add a new
feature or new datatype.

--

.NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.

Dec 11 '06 #10
Hi Peter,
>I do believe that deviating from an OO design is usually a poor choice,
but
if a switch isn't OO to begin with then I see no problem with just
keeping
the switch, as long as it's simple like the OP's original code sample.

If the switch statement is only ever evaluated once the choice between
keeping a switch statement or re-redesigning something "more" object
oriented
is somewhat moot. I would tend to err on the side of OO in this case; but
I
wouldn't fault someone for using a switch. Given the nature of the
question
I assumed the switch was being evaluated many times while the value of the
evaluation was constant. Given the choice between performing one
if/switch
at object creation then performing multiple lookups into a vtable for a
method and performing an if/switch multiple times, I would choose the
polymorphic route.
That's fair enough, but our immediate assumptions were obviously different
:)
>When
I see "switch" I don't automatically think "change is required",
especially
when it's perfectly obvious what the code is doing.

Agreed. And the example (that looked academic) didn't provide enough
information to accurately make a judgement whether going polymorphic would
offer any performance benefit, hence the "consider". It would be fairly
moot
whether "if" or "switch" was more performant in a repetitive situation if
you
can avoid repeating the evaluation altogether; but not enough information
was
given.
Fair enough as well.
>But the C# switch statement seems to provide optimizations that will
increase performance over "ifs", which are certainly required if an OO
solution is to be used to control flow based on user input or console
arguments.

To performance, there's nothing inherent in a switch statement that is any
faster than writing the most optimized set of if statements. Arguably you
could write equally just as performant gotos... Ifs would be more
maintainable than gotos, switches more maintainable than ifs, and, I
believe,
polymorphism would be more maintainable to switches.
Our opinions differ on the latter point in some cases; e.g., my example of a
switch that parses command-line arguments in a manner such as the OP's code
sample, I believe, is much clearer than an OO approach intended, solely, to
provide the same exact functionality.

As for your comment about performance, I can only say that I haven't tested
anything myself, but the articles I've cited seem to indicate that your
statement might not be accurate.

<snip>
>It's possible, and I'm not suggesting that it shouldn't be considered,
however I think that legibility, performance and ease of management are
also
worth consideration and switch may be the better solution at times, such
as
in the OP's original sample code. Scalability should also be of concern
and
a more OO pattern would help there, but I generally disagree with those
purists that you mentioned above - I really don't think that a simple
switch
statement is all that bad and I believe the OP's example is just that.

I don't think hoisting the switch into a factory and creating objects
based
on some value doesn't make it any less legible. Plus, simply adding
another
virtual method is all it takes to reuse that evaluation. The switch, as
written in the original example, could only be reused by
copy-paste-modify.
A switch statement on its own, of course, isn't bad.
I agree on most points here. I've commented on legibility above, which is
one place where I disagree with you for some particular circumstances. As
for the duplication of code, I've addressed that point in a response to Jon
Shemitz's post in this thread, but basically I agree. I just made different
assumptions than you about the OP's code to begin with, which I believe is
the usual cause that spawns discussions such as this (although we agree way
too much for this discussion to go on too much longer, I think :)

--
Dave Sexton
Dec 11 '06 #11
In 99% of the cases a switch is better than an if-statement and that is
because of the C# compiler will optimize a switch statement and can still
decide whether or not to implement the switch statement as an if-statement.
I agree that havign a long switch block should be refactored using a more OO
approach. See Martin Fowler's book on Refactoring.

Gabriel Lozano-Morán
The .NET Aficionado
http://www.pointerx.net

<msnews.microsoft.comwrote in message
news:eF**************@TK2MSFTNGP06.phx.gbl...
Is it fine to call another method from Switch?

Eg.

Switch (stringVar)
{
case ("a"):
somVar = "whatever";
Another_Method(); //call another method
return;
case ("g"):
somVar = "somethingelse";
Another_Method_2(); //call another method
return;
}

Is this a recommended approach or should it just be an if statement?

Dec 11 '06 #12
The most efficient solution for the case-insensitive comparation is:

if (string.Compare(stringVar, "aaaa", true,
CultureInfo.InvariantCulture) == 0)
// ...;
if (string.Compare(stringVar, "bbbb", true,
CultureInfo.InvariantCulture) == 0)
// ...;

Dec 11 '06 #13

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

Similar topics

6
by: Chris Mason | last post by:
I have an application that runs full screen on a system and I would like to be able to (at times) switch another program using an ALT-TAB like interface. However the system only has a touchscreen...
0
by: Mike Collins | last post by:
I apologize for using this newsgroup for what seems like a VB6 question, but I did not see a newsgroup for VB6. I also think I may not have the C# code setup correctly for calling from VB6. If...
5
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS...
1
by: jens Jensen | last post by:
Hello , i'm calling a webservice generated with oracle webservice java tools. I'm not able to add a web reference to a .net client the usual way with visual studio 2005. I was therefore...
18
by: John Friedland | last post by:
My problem: I need to call (from C code) an arbitrary C library function, but I don't know until runtime what the function name is, how many parameters are required, and what the parameters are. I...
4
by: sck10 | last post by:
Hello, I am trying to get the Month from the following using "switch" in my App_Code file. The error that I am getting is: An object reference is required for the nonstatic field, method, or...
3
by: Klaus | last post by:
Hi, I have an existing VC 6 MFC application which communicates asynchronly with a VC 2005 managed code dll. I use an unmanaged base class with virtual functions to access methods in the MFC...
10
by: SQACPP | last post by:
Hi, I try to figure out how to use Callback procedure in a C++ form project The following code *work* perfectly on a console project #include "Windows.h" BOOL CALLBACK...
8
by: Derek Hart | last post by:
I am unclear about what all the requirements are to call a simple vb.net application, installed in the GAC, from COM (such as writing vba in Word to call the dotnet dll). I believe I have...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...

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.