Better way to handle this long if, else-if structure.

Hi all,

I have a project that started out with a pretty simple if, else if structure, but over time it grew and now it's unweildy and just god-awful, and I'd like to fix it. I seem to remember attempting a switch statement before, but for some reason it didn't work. Here's an example of what it is.

1
2
3
4
5
6
7
8
9
10
11
12
13
void ProcessCommand(string inCommand)
{
  if(inCommand.find('=')!=string::npos) {
    string IOSAction = inCommand.substr(0,inCommand.find('=')); // What action
    string IOSCommand = inCommand.substr(inCommand.find('=')+1); // What command

    if (IOSAction == "loadplane") {
      // load the plane using IOSCommand.c_str()
    } else if (IOSAction == "reset")
      // reset scenario using sscanf(IOSCommand.c_str(), etc etc); to get params
    }
  }
}


I simplified this extensively to avoid confusion on my question, but there's about 30+ else if's on IOSAction in that one function. I use string, but I think that may be an additional step that doesn't need to happen. I use a lot of sscanf functions and atof functions and almost all of them involve converting back to c_str. I'd really like to break this up though, so I'm looking for ideas. Take me to the next level ;)

The ProcessCommand function is called from a UDP event callback that looks like this:

1
2
3
4
5
6
int bytesRead = mysocket->ReadData(inbuffer, 256, &inIP, &inPort);

if (bytesRead != -1) {
  string sbuffer = string(inbuffer).substr(0,bytesRead);
  ProcessCommand(sbuffer);
}
Switch statement only works with specific data types - and unfortunately string isn't one of them.
You could try using enum instead of string, or parse input and use something like Command pattern: http://gameprogrammingpatterns.com/command.html

Cheers!
That looks great, but I've not delved much into OOP yet...I really need to apparently. Is there a simpler way?
You could use std::map. You'd use input as a key, and look up for, let's say, an enum saying what command should be called. Keep in mind however, that maps aren't too fast. It will not matter in small projects, but if you find your code too slow - it may be the reason.

Cheers!
Last edited on
Topic archived. No new replies allowed.