Calling Method From Switch{}

G

Guest

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?
 
C

Carl Daniel [VC++ MVP]

msnews.microsoft.com said:
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
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Carl said:
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
 
G

Guest

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.
 
D

Dave Sexton

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 :)
 
G

Guest

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#
 
D

Dave Sexton

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/message.asp?p=1111&r=5445082

Here's a somewhat older thread:

http://groups.google.com/group/micr...statement+performance&rnum=8#e1398ce10221171b
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.
 
J

Jon Shemitz

Peter said:
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.
 
G

Guest

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/message.asp?p=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/micr...statement+performance&rnum=8#e1398ce10221171b

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.
 
D

Dave Sexton

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 said:
Peter said:
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.
 
D

Dave Sexton

Hi Peter,
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
:)
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.
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.

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 :)
 
G

Gabriel Lozano-Morán

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
 
K

Karras

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)
// ...;
 

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

Top