3 ms·
> There's one that's even closer to c-like switches: a list/tuple of functions or values, indexed by a small int. That sounds like a desperate plea to get stuc
by rualca 6y ago
> There's one that's even closer to c-like switches: a list/tuple of functions or values, indexed by a small int.
That sounds like a desperate plea to get stuck with a bug-riddled unmaintainable mess of a module.
If all you want to do is pick one of a finite set of possible code paths, it is never a good idea to generate a hash to pick from a map/array.
Even chained if/else if statements are cleaner than that mess.
- klyrs 6y agoI've seen it used in ways that make sense. They were small and well-contained, and definitely didn't involve computing a hash. For a not-small example, if you want to switch on an ascii character in a parser, you can make a 256-element list to implement your jump table, and index into it with ord. If you're performance-minded enough for this to make a lick of sense, you'll take care to only build the jump table once. And yeah, chained if/else is cleaner because it's the only tool that the language provides. The GP was asking for alternatives. They exist, but you'll hate them. Granted, you can speed the 256-long if/elif mess up with a binary if/else tree 8 levels deep. But it probably won't beat the jump table. If you truly find this upsetting, know that it's a practice that results from the language not supporting a switch statement.