Consider I'm interfacing with an external system that will send a message (DB table, message queue, web service) in some format. In the "message header" there is the "MessageType" that is a number from 1 to 20. The MessageType defines what to do with the rest of the message. There are things like new, modified, deleted, canceled...
My first inclination was to setup an enumeration and define all the types. Then parse the number into an enum type. With it as an enum I would setup the typical switch case system and call a particular method for each of the message types.
One big concern is maintenance.
A switch / case system is bulky and teadious but, it's really simple.
Various table / configuration systems can be difficult for someone else to grok and add new messages or tweak existing messages.
For 12 or so MessageTypes the switch/case system seems quite reasonable. What would be a reasonable cut-off point to switch to a table driven system?
What kinds of systems are considered best for handling these types of problems?
I'm setting a tag for both C# and Java here because it's definitly a common problem. There are many other languages with the same issue.
In Java, you can make it an enum and give behaviour to the different values (although with 100 values, I'd hope that each type of behaviour is briefly, calling out to "proper" classes).
In C#, you can have a map from value to some appropriate delegate type - then when you statically construct the map, you can either use lambda expressions or method group conversions as appropriate.
Having said that, setting up the map is going to be just as ugly as a switch statement. If each switch statement is just a single method call, you might like to try this sort of format:
switch (messageType)
{
case 0: HandleLogin(message); break;
case 50: SaveCurrentDocument(message); break;
case 100: HandleLogout(message); break;
}
(etc). I know it's against normal conventions, but it can be quite neat for the odd exceptional situation like this. If you only need the numbers in one place, then there's little point in introducing constants - basically the line containing the number effectively is the constant definition!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With