Switch replaces if-else for a cleaner code

Samarth Dhroov
2 min readMay 17, 2021

--

If you have not yet seen the previous day’s article, Kindly do so here.

As seen before, the if-else loop came to the rescue while handling an increasing number of power boosters. But, that solution seems less scalable as far as the speed of writing the code is concerned.

Therefore, there is a little cleaner way to work out the same solution with a possibility of smooth additions into the list, as the game grows.

Here is a replacement using another construct of programming, known as a switch statement.

A switch code block works in a similar fashion to how electric switchboards work in our offices or houses.

For instance, if you want to turn on your coffee brewer, you are going to plug that machine into the wall and then flip the switch right beside it. In the exact same way, we write code that works like wall blocks and depending on the program, relevant switches are turned on.

Below is the if-else implementation.

if (_powerupId == 0)
{
player.isTripleShotActive();
}
else if (_powerupId == 1)
{
Debug.Log("Speed booster achieved.");
}
else
{
Debug.Log("Shield booster achieved.");
}
Destroy(this.gameObject);

The switch statement for the same block of code is shown below.

private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Player")
{
switch (_powerupId)
{
case 0:
player.isTripleShotActive();
break;
case 1:
Debug.Log("Speed booster achieved.");
break;
case 2:
Debug.Log("Shield booster achieved.");
break;
default:
Debug.Log("Default Value");
break;
}
Destroy(this.gameObject);
}

As clearly visible, the code above is so well understandable, scalable, and resilient to human errors compared to the sloppier version of the if-else block which could introduce bugs.

So, the bottom line is when there is a chance of extensive outcomes being made from a single choice, utilize the switch case statement rather. In other scenarios, the if-else would suffice the need.

Thank you very much

--

--

No responses yet