mardi 4 septembre 2018

Minimizing amount of if/else if statements

I'm currently programming a speech tool in a project at my university. I got the advice to cut the amount of if/else if statements, but i can't think about another way solving it except maybe switch/case.

Every Voice Output is different and the Coroutines need different Paramaters based on the train type. So i don't know how to simplify those. Are there special methods / best practices in C# to solve problems like this?

The Application is developed in Unity wiht the Microsoft Speech API

So the statements are like

else if (spokenText.IndexOf("Wo") > 0)
    {
        if (spokenText.IndexOf("Bahn") > 0 || spokenText.IndexOf("Zug") > 0)
        {
            //Ask for Train
        }
        else if (spokenText.IndexOf("nächste") > 0 && (spokenText.IndexOf("RE") > 0 || spokenText.IndexOf("S-Bahn") > 0 || spokenText.IndexOf("ICE") > 0) || spokenText.IndexOf(" S ") > 0
            || spokenText.IndexOf("IC") > 0 || spokenText.IndexOf("EC") > 0)
        {

            if (spokenText.IndexOf("ICE") > 0)
            {
                //Start Coroutine
            }
            else if (spokenText.IndexOf("EC") > 0)
            {
               // Start Coroutine with different Parameter
            }
            else if (spokenText.IndexOf("IC") > 0)
            {
            //Start Coroutine with different Parameter
            }
        }
        else
            // Voice output
    }
    else if (spokenText.IndexOf("Wann") > 0)
    {
        if ((spokenText.IndexOf("Zug") > 0 || spokenText.IndexOf("Bahn") > 0) && spokenText.IndexOf("nächste") > 0 && spokenText.IndexOf("nach") > 0)
        {
            // Coroutine
        }
        else if (spokenText.IndexOf("Zug") > 0 || spokenText.IndexOf("Bahn") > 0)
        {
            // Voice output
        }

        else if (spokenText.IndexOf("nächste") > 0 && (spokenText.IndexOf("RE") > 0 || spokenText.IndexOf("S-Bahn") > 0 || spokenText.IndexOf("ICE") > 0) || spokenText.IndexOf(" S ") > 0
            || spokenText.IndexOf("IC") > 0 || spokenText.IndexOf("EC") > 0)
        {

            if (spokenText.IndexOf("ICE") > 0)
            {

               // Coroutine
            }
            else if (spokenText.IndexOf("EC") > 0)
            {
              //Coroutine
            }
            else if (spokenText.IndexOf("IC") > 0)
            {
              //Coroutine
            }
        }
        else
            //Voice Output

    }
    else if (spokenText.IndexOf("Barrierefrei") > 0 || spokenText.IndexOf("Aufzug") > 0 || spokenText.IndexOf("Rolltreppe") > 0)
    {
        //Coroutine
    }
    else {
        //Voice Output
    }
}

Aucun commentaire:

Enregistrer un commentaire