Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I improve this C++ code

I want your suggestion on the following pseudo-code. Please suggest how could I improve it, whether or not I could use some design patterns.


// i'm receiving a string containing : id operation arguments
data    = read(socket);
tokens  = tokenize(data," "); // tokenize the string based on spaces
if(tokens[0] == "A") {
   if(tokens[1] == "some_operation") {
      // here goes code for some_operation , will use the remaining tokens as arguments for function calls
   }
   else if(tokens[1] == "some_other_operation") {
     // here goes code for some_other_operation , will use the remaining tokens
   }
   ...
   else {
     // unknown operation
   }
}
else if(tokens[0] == "B") {
   if(tokens[1] == "some_operation_for_B") {
     // do some operation for B
   }
   else if(tokens[1] == "yet_another_operation") {
     // do yet_another_operation for B
   }
   ...
   else {
     // unknown operation
   } 
}

I hope you get the point . The thing is I have a large number of id's and each has it's own operations , and I think it's kinda ugly to have 10 screens of code containing a lot of if's and else if's.

like image 438
Geo Avatar asked Oct 27 '08 08:10

Geo


1 Answers

Have a class for each ID which implements a common interface. Basically the Strategy pattern IIRC.

So you'd call (pseudo)code like:

StrategyFactory.GetStrategy(tokens[0]).parse(tokens[1..n])

like image 94
Epaga Avatar answered Nov 15 '22 20:11

Epaga