Doers of Stuff.org

A place to Do Stuff and see Stuff Done…

Switch Statements to the Rescue

What is a program? It is a series of procedures, branches and loops. That’s really all it is. The front line of branching is the if(){} statement. You check for some condition and only perform the code based on the condition checked. The else{} clause however I like less, though removing it takes more than a bit of finesse. The if else(){} clause however is totally offensive. Aesthetically, it looks and feels sloppy and misdirected. Kind of like you don’t really know what is going on, so you have to play twenty questions.

When it can be used, the switch statement is a more elegant solution. However, each programming language treats the switch statement differently. In C#, you “switch” on a single variable. Each “case” represents a code branch based on a particular value for the given variable. When you are done with that branch of code, you “break” out of entire clause.

In our Player class, we use a switch statement to branch our code path based on the colliding game object’s tag. To keep the switch statement compact, we make each branch a method call.

private void OnTriggerEnter2D(Collider2D other)        
{ 
    switch (other.tag)
    {
        case "Enemy":
            TakeDamage();
            break;
        case "TripleShotPU":
            if (!tripleShot) { StartCoroutine(PowerUpTripleShot()); }
            break;
        case "SpeedPU":
            if (speedUp == 0) { StartCoroutine(PowerUpSpeed()); }
            break;
        default:
            break;
    }
}

As we add new game objects capable of colliding with the Player, we expand the switch statement.

Strictly speaking, the if(){}else if(){}else{} clause is no different than the switch. In fact, they probably compile the same. But I always have and still do consider programming more art than engineering or science. So visual appeal is important to me.

Leave a Reply

Switch Statements to the Rescue

by Robert time to read: 1 min
0