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.