Freitag, 15. Juni 2012

A better world with a better switch statement

It is known that using switch statements should, in most cases, be replaced by polymorphism when using object oriented languages (refer to Clean Code by Robert Martin, Code Smell G23).

But you must stay pragmatic as well, and sometimes the switch statement is an option. But: why must it's C# syntax look like this? Why is it so inconsistant with the rest of the language? Why do we have to write break?

I imagine a switch-statement like this:

switch (selector)
{
  case (value)
  { ... }

  case (other value || still other value)
  { ... }

  case (new List<>() { a, b, c })
  { ... }

  default 
  { ... }
}

So no ':' that reminds me of lables. No break after each case - use the well known block delimiter instead. Write the argument to the case keyword in braces as like with if, while, for and others. Do not stack control structures but use known logical operators / lists to combine cases.

Would this not be nice?



Keine Kommentare:

Kommentar veröffentlichen