Skip to content

Commit 8ac0a32

Browse files
authored
Merge pull request chuanxshi#62 from norlin/master
Switch is antipattern!..
2 parents 1a18057 + cb92bc0 commit 8ac0a32

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

general-patterns/switch-pattern.html

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
* the cases matched.
2222
*/
2323

24+
//antipattern
2425
var inspect_me = 0,
2526
result = '';
2627
switch (inspect_me) {
@@ -34,6 +35,33 @@
3435
result = "unknown";
3536
}
3637

38+
//preferred 1,
39+
//'cause it is much faster and easy to reuse and read
40+
//avoid to use switch
41+
var results = {
42+
0: "zero",
43+
1: "one"
44+
};
45+
46+
result = results[inspect_me] || "unknown";
47+
48+
//preferred 2
49+
var resultFuncs = {
50+
0: function () {
51+
//some code for "zero" case
52+
return "zero";
53+
},
54+
1: function () {
55+
//some code for one case
56+
return "one";
57+
}
58+
};
59+
60+
result = (resultFuncs[inspect_me] || function () {
61+
//some code for default case
62+
return "unknown";
63+
})();
64+
3765
// References
3866
// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
3967
</script>

0 commit comments

Comments
 (0)