Switch Statements to the Rescue

by Lance Gold

Use switch statement to avoiding difficult to read if-then-else logic

Return to index

Here is the usual if-then-else code:


                if( _powerupID == 0 )
                {
                    player.TripleShotActive();
                } 
                else if( _powerupID == 1 )
                {
                    Debug.Log("speed collected"); // player. speed()
                }
                else if( _powerupID == 2 )
                {
                    Debug.Log("collected shield"); // player. shield()
                }

A switch statement is helpful to make the decision tree look like a table:


                switch (_powerupID)
                {
                    case 0:
                        ;
                        break;
                    case 1:
                        ;
                        break;
                    case 2:
                        ;
                        break;
                    default:
                        ;
                        break;
                }

and so adding the Debug.log message logic:


                switch ( _powerupID )
                {
                    case 0:
                        player.TripleShotActive();
                        break;
                    case 1:
                        Debug.Log("speed collected"); // player. speed();
                        break;
                    case 2:
                        Debug.Log("collected shield"); // player. shield();
                        break;
                    default:
                        ;
                        break;
                }