Trying to figure out how I might optimize the following method.
void DoParse(string val)
{
val = val.Trim().ToLower();
if(val.IndexOf("run")!= -1)
{
//do run
}
if (val.IndexOf("walk") != -1)
{
//do walk
}
if (val.IndexOf("lie down") != -1)
{
//do down
}
if (val.IndexOf("stand up") != -1)
{
//do up
}
if (val.IndexOf("stealth") != -1)
{
//do stealth
}
if (val.IndexOf("right") != -1)
{
//do right
}
if (val.IndexOf("left") != -1)
{
//do left
}
}
- You can use
string.Contains()
to check if a sequence of characters exists instead of string.IndexOf() != -1
- Assuming only one of these conditions can be run depending on what the value of “val” is, you should be using
else if
statements or switch case
statements to avoid checking for more conditions after one condition has already been satisfied.
One question also; is “val” supposed to be a string of text that can contain the conditions you’re checking for, or will it only contain these conditions?
For example, is it possible for it to be something like, "I am going to run down the street"
, and you’re checking if one of those key-words exists in this statement, or would it always just be one of those key words like "run"
?
If it’s the latter, then you can use enums instead to define a constant set of states and use them instead of a string value.
Something like this might be how I’d refactor it with these conditions:
enum State {
RUN,
WALK,
LIE_DOWN,
STAND_UP,
STEALTH,
RIGHT,
LEFT
}
void DoParse(State state) {
switch(state) {
case State.RUN:
//do run
break;
case State.WALK:
//do walk
break;
case State.LIE_DOWN:
//do lie down
break;
case State.STAND_UP:
//do stand up
break;
case State.STEALTH:
//do stealth
break;
case State.RIGHT:
//do right
break;
case State.LEFT:
//do left
break;
}
}
Or if it’s the former case and you need to use a string value for this instance:
void DoParse(string val) {
if(val.Contains("run")) {
//do run
}
else if(val.Contains("walk")) {
//do walk
}
else if(val.Contains("lie down")) {
//do lie down
}
else if(val.Contains("stand up")) {
//do stand up
}
else if(val.Contains("stealth")) {
//do stealth
}
else if(val.Contains("right")) {
//do right
}
else if(val.Contains("left")) {
//do left
}
}