#MonthOfCode - Day 10: switch

My entry for the 10th day of the month of code. The theme for today is: switch.

Today, the code is just an usage of the switch statement that you might not know.

Code after the break.

You can switch on the value true and use conditions in the case statements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

switch (true) {
case 0 < price && price <= 5:
// do something
break;
case 5 < price && price <= 10 && customer.hasLoyaltyCard():
// do something
break;
case 5 < price && price <= 10 && !customer.hasLoyaltyCard():
// do something
break;
case 10 < price:
// do something
break;
}

It’s equivalent to a series of if-elseif statements. It’s only a matter of style. On notable difference is when you have lots of ||. There can be turned into multiple case statements:

1
2
3
4
5
6
7
8
9

switch (true) {
case user.isRoot():
case user.hasRole('editor'):
case user.isOwner(file):
case user.canRead(file):
// do something
break;
}