New Perspectives On Web Design

(C. Jardin) #1

CHAPTER 2 Writing Maintainable, Future-Friendly Code


switch(value) {
case 1:
doSomething();
case 2:
doSomethingElse();
break;
default:
doDefaultThing();
}

The first case falls through into the second case so if value is 1, then
both doSomething() and doSomethingElse() are executed. And here’s the
question: is there an error here? It’s possible that the developer forgot to
include a break in the first case, but it’s also equally possible that the devel-
oper intended for the first case to fall through to the second case. There’s
no way to tell just from looking at the code.
Now suppose you have a JavaScript style guide that says something
like this:

All switch statement cases must end with break, throw, return,
or a comment indicating a fall-through.

Judging by this guideline, there is definitely a stylistic error and that
means there could be a logic error. If the first case was supposed to fall
through to the second case, then it should look like this:

switch(value) {
case 1:
doSomething();
// falls through
case 2:
doSomethingElse();
break;
default:
doDefaultThing();
}
Free download pdf