Reputation: 10538
I was wondering, how can I avoid a giant switch statement when trying to handle code received from a network source? The message comes in with an opcode (int), with the function to be called depending on aforementioned opcode (not my design, and I can't influence it).
I need to call a function in response to the opcode, but I don't necessarily want to have to hard-code the opcode to function mapping using a switch statement, because that would make it rigid and hard to fix if the network schema changes.
tldr how can I tie an int to a function - noting that the functions may be distributed across the entire solution (each message may require different state information/may belong to a different class) Right now I have marked functions with attributes, but is there a better way of doing this?
Upvotes: 3
Views: 68
Reputation: 10507
There are definately a few different ways to handle it... However, as usually, the hard-code will actually provide the FASTEST output.
But, if you can handle a little extra latency (and I definately mean a little...) you could try a Dictionary<int, TMessage>
.
I would recommend that the type TMessage
have a method that would be able to read it's self in. Meaning the code would first read the "op code", use it to pick out the TMessage
, and then have the message read the rest in.
If you wanted to get fancy... you could use reflection
to populate the dictionary, so you don't have to hardcode ANYTHING.
Upvotes: 0
Reputation: 10958
Assuming all your functions have the same signature MyFunctionDelegate
you can use a Dictionary<int, MyFunctionDelegate>
which maps ints to the methods.
If the opcodes range from 0 to N with no gap you can also use a simple array or list.
Upvotes: 1
Reputation: 62482
Use a Dictionary
to map the int to a handler:
var handlers=new Dictionary<int,Action<NetworkData>>();
handlers[Opcode.Foo]=HandleFoo;
handlers[Opcode.Bar]=HandleBar;
void HandleFoo(NetworkData data)
{
// Whatever
}
void HandleBar(NetworkData data)
{
// Whatever
}
Upvotes: 3