How to refactor hundreds of conditions in chain without using if and switch statements for each cases?

Viewed 89

I am developing an AI text communication engine, and I was wondering if anyone point me in the direction of a more efficient approach to validating user input other than just switch / if statements.

This is the foundation of it:

void Update(){
    string s = Console.Read()s.ToLower();

    if (s == "c1"){
        // do 1
    }
    else if (s == "c2"){
        // do 2
    }

    ...

    else if (s == "c9342"){
        // do 9342
    }
}

I should add, I have the ability to check for keywords in the sentence.

I feel like due to the fact that all input is strings, and it is dealing with language, this may be the only way to go, but if anyone has any better approach eg. interfaces, custom types, reflection, threading or anything then I am all ears.

Thanks, Andy

1 Answers

Andy! You can work with delegates to achieve that flexibility. Delegates are a little complex and not as fast as a "direct" code, but they have their value.

Here I'm assuming that your comparison object will always be a string (and a lot of other stuff, if this solution doesn't fit your need, please leave a comment so we can work on that).

// Create a dictionary where the key is your comparison string and
// the action is the method you want to run when this condition is matched
Dictionary<string, Action> ifs = new Dictionary<string,Action>()
{
    // Note that after the method name you should not put () 
    // otherwise you would be invoking this method instead of create a "pointer" 
    {"c1", ExecuteC1},
    {"c2", ExecuteC2},
    {"c9342", ExecuteC9342},
}

private void ExecuteC1()
{
    Console.WriteLine("c1");
}    

private void ExecuteC2()
{
    Console.WriteLine("c2");
}    

private void ExecuteC9342()
{
    Console.WriteLine("c9342");
}

public RunCondition(string condition)
{
   // Get the condition related value by its key and calls the method with 'Invoke()'
   ifs[condition].Invoke();
}    
Related