Permalink
Switch branches/tags
Nothing to show
Find file Copy path
70 lines (62 sloc) 1.72 KB
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: switch Pattern
Description: improve the readability and robustness of your switch statements
*/
/* Style conventions:
* 1. Aligning each `case` with `switch` (an exception to the curly braces indentation rule).
* 2. Indenting the code within each case.
* 3. Ending each `case` with a clear `break`;.
* 4. Avoiding fall-throughs (when you omit the break intentionally). If you're absolutely convinced
* that a fall-through is the best approach, make sure you document such cases, because they might
* look like errors to the readers of your code.
* 5. Ending the `switch` with a `default`: to make sure there's always a sane result even if none of
* the cases matched.
*/
//antipattern
var inspect_me = 0,
result = '';
switch (inspect_me) {
case 0:
result = "zero";
break;
case 1:
result = "one";
break;
default:
result = "unknown";
}
//preferred 1,
//'cause it is much faster and easy to reuse and read
//avoid to use switch
var results = {
0: "zero",
1: "one"
};
result = results[inspect_me] || "unknown";
//preferred 2
var resultFuncs = {
0: function () {
//some code for "zero" case
return "zero";
},
1: function () {
//some code for one case
return "one";
}
};
result = (resultFuncs[inspect_me] || function () {
//some code for default case
return "unknown";
})();
// References
// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
</script>
</body>
</html>