In many programming languages, the
switch statement has been something I’ve been doing lately.
What is the switch statement?
If you’ve not used
switch before or are a little unsure what it does, let’s walk through it. What
switch does is take input and provide an output, such as code being run.
Let’s look at a usual
It’s similar to
else statements, but it should evaluate a single value - inside the
switch we use a
case to evaluate against each value.
When you start seeing lots of
else if statements, something is likely wrong and generally you shoud use something like
switch as it’s more suited for the purpose and intention. Here’s some
else if abuse:
This implementation is too loose, there is room for error, plus it’s a very verbose syntax to keep repeating yourself. There’s also the room for hacks as you can evaluate multiple expressions inside each
else if, such as
else if (type === 'coke' && somethingElse !== 'apples'). The
switch was the best tool for the job, albeit you need to keep adding
break; statements to prevent cases falling through, one of its many issues.
Problems with switch
There are multiple issues with
break; statements within each
case, which can lead to difficult debugging and nested errors further down the case should we forget! Douglas Crockford has written and spoken about it numerous times, his recommendations are to treat it with caution.
switch for - so why not use an Object literal to replace
switch? Objects are much more flexible, have better readability and maintainability and we don’t need to manually
As the number of “cases” increases, the performance of the object (hash table) gets better than the average cost of the switch (the order of the cases matter). The object approach is a hash table lookup, and the switch has to evaluate each case until it hits a match and a break.
Object Literal lookups
We use Objects all the time, either as constructors or literals. Often, we use them for Object lookup purposes, to get values from Object properties.
Let’s set up a simple Object literal that returns a
String value only.
We’ve saved a few lines of code from the switch, and to me the data is a lot cleaner in presentation. We can even simplify it further, without a default case:
We might, however, need more complex code than a
String, which could hang inside a function. For sake of brevity and easy to understand examples, I’ll just return the above strings from the newly created function:
The difference is we need to call the Object literal’s function:
More maintainable and readable. We also don’t have to worry about
break; statements and cases falling through - it’s just a plain Object.
Usually, we would put a
switch inside a function and get a
return value, so let’s do the same here and turn an Object literal lookup into a usable function:
Nice and easy, but this doesn’t cater for a “default”
case, so we can create that easily:
We could simplify the above
else using the or
|| operator inside an expression:
This wraps the two Object lookups inside parenthesis
( ), treating them as an expression. The result of the expression is then invoked. If
drinks[type] isn’t found in the lookup, it’ll default to
We don’t have to always
return inside the function either, we can change references to any variable then return it:
These are very basic solutions, and the Object literals hold a
function that returns a
String, in the case you only need a
String, you could use a
String as the key’s value - some of the time the functions will contain logic, which will get returned from the function. If you’re mixing functions with strings, it might be easier to use a function at all times to save looking up the
type and invoking if it’s a function - we don’t want to attempt invoking a
Object Literal “fall through”
switch cases, we can let them fall through (which means more than one case can apply to a specific piece of code):
pepsi “fall through” by not adding a
break statement. Doing this for Object Literals is simple and more declarative - as well as being less prone to error. Our code suddenly becomes much more structured, readable and reusable:
switch is a bit old and clunky and prone to difficult debugging errors. Objects are more extensible, maintainable, and we can test them a lot better. They’re also part of a design pattern and very commonly used day to day in other programming tasks. Object literals can contain functions as well as any other Object type, which makes them really flexible! Each function in the literal has function scope too, so we can return the closure from the parent function we invoke (in this case
getDrink returns the closure).
Some more interesting comments and feedback on Reddit.