Monday, September 22, 2014

Enhanced syntax for switch statements (and if statements)

The switch statement syntax has always bothered me since it introduces two levels of indentation:

   switch (value)
   {
      case 0:
      case 1:
         doThis();
         break;
      case 2:
      case 3:
         doThat();
         break;
      default:
         doSomethingElse();
   }

Of course one could reduce the indentation. It would look a bit unusual but it could work:

   switch (value) {
   case 0:
   case 1:
      doThis();
      break;
   case 2:
   case 3:
      doThat();
      break;
   default:
      doSomethingElse();
   }

Let's instead write this with an if statement. It is, arguably, easier to read:

   if (value == 0 || value == 1)
      doThis();
   else if (value == 2 || value == 3)
      doThat();
   else
      doSomethingElse();

Even with curly brackets the if statement kind of looks cleaner than the switch statement:

   if (value == 0 || value == 1)
   {
      doThis();
   }
   else if (value == 2 || value == 3)
   {
      doThat();
   }
   else
   {
      doSomethingElse();
   }

But let's think about it for a while. Let's be creative. We could make an enhanced switch statement:

   switch (value) case (0, 1)
      doThis();
   case (2, 3)
      doThat();
   default:
      doSomethingElse();

The enhanced switch statement looks a whole lot like an if statement. How about we enhance the if statement instead:

   if (value == 0, 1)
      doThis();
   else if (2, 3)
      doThat();
   else
      doSomethingElse();

Hey, this looks good! I wonder if it would be possible to write an IntelliJ plugin (or ReSharper plugin) for this kind of syntax enhancement? I guess I gotta find out.


Archive