6 ms·
The author's basic complaint with the Javascript switch statement is that it's essentially a structured series of 'goto' statements. They think that each 'case
by rovolo 8y ago
The author's basic complaint with the Javascript switch statement is that it's essentially a structured series of 'goto' statements. They think that each 'case' should behave as an 'if-else' where each case has its own lexical scope, and the control flow doesn't leak from one case to another. They think that pattern matching is a better model for 'switch' in practice.
How often do you use a 'switch' statement whose cases don't always end in 'return' or 'break'? The "coroutines in C" [0] article is a clever use of switch-case as a goto, but it seems like you need to invent new types of control flow to use 'goto' properly. Does anyone have other clever uses of 'switch'?
[0] https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
- ioddly 8y ago> How often do you use a 'switch' statement whose cases don't always end in 'return' or 'break'? I do, occasionally. I prefer the inverted golang switch where fallthrough needs to be specified, since these cases (heh) are generally the minority.
- xahrepap 8y agoI would like it better if switch statements used the keyword `continue` to fallthrough and `break` is implied. Switch statements are much easier to maintain if you keep them one or two lines long, and just have it immediately delegate to a function call then break. I think that's true for almost any code-flow syntax: if/elseif/else blocks, various loops. They all break down quickly if you have too much in them.
- ivyirwin 8y agoI agree. Their complaint on the use cases (pun!) for switch seem to ignore the flexibility of the syntax. I don't think the requirement to include breaks/returns is a problem if you know how it's intended to work. I prefer switches for the easy to follow flow but also the ability to "waterfall" multiple conditions, which is syntactically clunky with other approaches.
- ricardobeat 8y agoThis is my favorite from a library I wrote ~6 years ago: https://github.com/ricardobeat/require-tree/blob/master/index.js#L16-L22 https://github.com/ricardobeat/require-tree/blob/master/inde... The goal is to accept a 'filter' argument that can either be a string, an array of strings, a regular expression, or a filter function. It fully uses fall-through and the multiple entry points. I find it magical, in that it turns all of those into a function so the remainder of the code doesn't have to care, and it's not any less efficient. Similar feeling to finding a use case for 'Infinity' :) switch (type(filter)) { case 'array' : filter = filter.join('|') case 'string' : filter = new RegExp('^('+filter.replace('*', '.*')+')$', 'i') case 'regexp' : filter = filter.exec.bind(filter) case 'function' : return filter }
- fc88 8y agoThis is one of the most amazing pieces of code I have ever seen