Large Switch statements: Bad OOP?

Posted by Mystere Man on Stack Overflow See other posts from Stack Overflow or by Mystere Man
Published on 2009-02-02T23:39:41Z Indexed on 2010/12/30 1:54 UTC
Read the original article Hit count: 174

Filed under:
|
|
|

I've always been of the opinion that large switch statements are a symptom of bad OOP design. In the past, I've read articles that discuss this topic and they have provided altnerative OOP based approaches, typically based on polymorphism to instantiate the right object to handle the case.

I'm now in a situation that has a monsterous switch statement based on a stream of data from a TCP socket in which the protocol consists of basically newline terminated command, followed by lines of data, followed by an end marker. The command can be one of 100 different commands, so I'd like to find a way to reduce this monster switch statement to something more manageable.

I've done some googling to find the solutions I recall, but sadly, Google has become a wasteland of irrelevant results for many kinds of queries these days.

Are there any patterns for this sort of problem? Any suggestions on possible implementations?

One thought I had was to use a dictionary lookup, matching the command text to the object type to instantiate. This has the nice advantage of merely creating a new object and inserting a new command/type in the table for any new commands.

However, this also has the problem of type explosion. I now need 100 new classes, plus I have to find a way to interface them cleanly to the data model. Is the "one true switch statement" really the way to go?

I'd appreciate your thoughts, opinions, or comments.

© Stack Overflow or respective owner

Related posts about c#

Related posts about oop