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.
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])
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