Best way to avoid a thousand if statements?

1.8k Views Asked by At

I basically have this problem: right now, we have a system where it gets a string as input, and it basically says ACTION:.

For each of the actions there is an automatically generated function(Rational Rose GRRR), such as

bouncer_comm.chatMessage("data goes here").sendAt(msg->sapIndex0());
bouncer_comm.askforname().sendAt(msg->sapindex0());

bouncer_comm returns an RTOutSignal, I can't create them manually because of the bizarre structure rose uses.

Right now, my only option is to create a hundred or so if statements, where I do:

if(action == "CHAT")  bouncer_comm.chatMessage("data goes here").sendAt(msg->sapIndex0());

Which is realllllyy annoying.

What would be the best way to avoid this? I've looked at / tried countless things, this is a really old version of rational rose (pre 2k) and yeah.

If anyone has any ideas that would be amazing.

5

There are 5 best solutions below

2
On BEST ANSWER

I like @cobbal's idea of the function pointer hash above, but you could replace this conditional logic with polymorphism.

see: http://c2.com/cgi/wiki?ReplaceConditionalWithPolymorphism

4
On

A hash storing function pointers could work well here

0
On

You could use boost::bind or boost::function and a map. This would allow you to call the correct function, even know each function has a different amount of parameters.

If you don't want any extra code you could use function objects and inheritance.

0
On

I used polymorphism combined with the factory pattern. I reduced a lot of if's to this :


MyAbstractClass *ac = Factory::getHandlerFor(data);
ac->perform(parameters);
0
On

I think the easiest is a map of boost::functions.