News for hackers. Stuff that matters.
Re:Why I prefer objects over switch statements by sklivvz1971 on Friday February 22, 2019 @12:05PM (#19226916)
Firstly, switches are arguably way, way (waaaay!) more readable than the code proposed. It's a matter of taste for sure, but arguably a basic construct of all curly languages and more is easier to understand than a rather esoteric code where a pattern is substituted for a keyword. Of course though, it is true that switch statements in JavaScript have issues with breaks and code blocks, but any half decent linter will tell you about those.

Most importantly though, the performance profile of the solution proposed scares me a lot. To understand why, consider that it is not uncommon for switches to be JITted as:

- If statements and gotos for small number of options or - Collections of lambdas for high number of choices (note, much more optimized than the lambdas proposed, very likely!)

The reason they are built this way is performance (another commenter ...commented that performance doesn't matter - they are wrong, a switch can be nested in a hot loop ran millions of times and they do matter). Therefore, it's easily arguable that the presented pattern will significantly worse in some cases (few choices) and that should not be underestimated.

Re:Why I prefer objects over switch statements by lucideer on Friday February 22, 2019 @03:46PM (#19228948)
> switches are arguably way, way (waaaay!) more readable than the code proposed

The point in the article is not that switches are less readable, but that switches can be "less" readable. Or—more accurately—they can look like they're readable but obscure unexpected subtleties

The object syntax may be slightly less readable than the switch in its simplest, most well-written form, but the point is that unlike the switch, it always unambiguously does what you expect.

It's also worth noting that the object syntax is extremely idiomatic in modern JS. It may look less readable to a generalist, but to anyone regularly maintaining JS it's far more familiar than the switch. (I guess this isn't so much a point in it's favour, it's more a point against modern JS being easy to pick up, but hey).

> it is true that switch statements in JavaScript have issues with breaks and code blocks, but any half decent linter will tell you about those.

While you have a point about linters, and I do use a strict one in every project, I'm much more comfortable with it being a safety net than the first line of defence.

Also, those problems with breaks and code blocks are hardly unique to JavaScript.

Re:Why I prefer objects over switch statements by rojobuffalo on Friday February 22, 2019 @12:24PM (#19227097)
switch statements are way more readable than what is demonstrated in the article. It's not even close.
Re:Why I prefer objects over switch statements by gramstrong on Friday February 22, 2019 @12:39PM (#19227241)
I disagree :) It's easier for me to look at an object and its contents and see where it is referenced. I think switch statements are ugly. I think if/else blocks are ugly. I prefer boolean statements when possible, although definitely not nested ternaries.

I'm sure I'll get flamed, but I really liked this:

  const getPosition = position =>
      ({
          first: 'first',
          second: 'second',
          third: 'third'
      }[position] || 'infinite');
Re:Why I prefer objects over switch statements by lhorie on Friday February 22, 2019 @01:06PM (#19227518)
I think equating ugly with hard-to-read is a common mistake. Many things are "ugly" but easy to read (e.g. in design circles, newbies often do far-too-small fonts with low contrast because it looks pretty, whereas accessibility guidelines tell you to do the opposite; in programming, readability of point-free style has more to do with the reader's ML-vs-Algol experience than how elegant FP may be, and educators often start w/ procedural style precisely because reading the flow of the program matches the students' expectations that things ought to be read top to bottom, rather than peeled through layers of abstractions)

Honestly, I find that rating the readability of the object versions vs the switch statement is bikeshedding. This is perfectly readable and doesn't involve going back and forth with my eyes to figure out the data flow or figure out if I have mismatched brackets or what have you:

    const getPosition = position => {
      switch (position) {
        case 'first':
        case 'second':
        case 'third':
          return position;
        default:
          return 'infinite';        
      }
    }
Another thing that is worth mentioning is that objects consume memory and allocating memory in JS for this is just wasting orders of magnitudes more cycles and sacrificing throughput for no good reason - other than to try to be clever and avoid an idiomatic and optimizable construct.
Re:Why I prefer objects over switch statements by gramstrong on Friday February 22, 2019 @05:48PM (#19229861)
>I think equating ugly with hard-to-read is a common mistake

This is just a semantics argument. I can replace "ugly" with "hard-to-read" if you want. I think it's both, in this instance.

>Honestly, I find that rating the readability of the object versions vs the switch statement is bikeshedding.

I agree in the context of code review, but since this is what we're talking about I figured I'd share my opinion.

>Another thing that is worth mentioning is that objects consume memory and allocating memory in JS for this is just wasting orders of magnitudes more cycles and sacrificing throughput for no good reason - other than to try to be clever and avoid an idiomatic and optimizable construct.

Premature optimization. If you need to optimize, then do it. Otherwise you should prioritize what you consider understandable and easy-to-write code. I guarantee the vast majority of javascript written would not be ill-affected by this.

Re:Why I prefer objects over switch statements by lhorie on Saturday February 23, 2019 @01:54PM (#19234864)
I'd ask you to reconsider what an optimization is, and to also consider the concept of "premature cleverification".

A switch statement is a pretty idiomatic choice for the example. Merely knowing more about the low level cost of different options does not make a snippet an optimization.

Examples of actual optimizations (from real world code I've seen) would include using bitmaps, lookup tables, large regexps, tries and binary search. All of these have the property of obscuring the search space in the name of performance, and many come with trade-offs such as increased startup cost or code size. Choosing to use a trie here, for example, without considering its trade offs would be a premature optimization. A switch statement is at worst a refactor that maintains the same algorithm.

Re:Why I prefer objects over switch statements by dymk on Friday February 22, 2019 @02:43PM (#19228453)
What happens when your values are computed? Or expensive to compute, and your map starts to get big? E.g.:

    {'a': foo(), 'b': bar() }[...]
If foo() or bar() ever introduce side-effects or become expensive, you're gonna have a hell of a time figuring out what's going wrong.
Re:Why I prefer objects over switch statements by Riobe on Friday February 22, 2019 @03:58PM (#19229044)
If your values are expensive to compute like that, then you'd have the object return a function that would call foo(), bar(), and so on; and you wouldn't call them all to setup the map in the first place.
Re:Why I prefer objects over switch statements by Izkata on Friday February 22, 2019 @05:12PM (#19229625)
This is in fact demonstrated in the second example in "Working with functions"...
Re:Why I prefer objects over switch statements by chris11 on Friday February 22, 2019 @01:59PM (#19228040)
My personal preference is if-else/switch blocks with enums. Doing conditionals with string parsing just seems gross to me, but I find conditionals easy to read. And the benefits of using an enum is that you can easily find where it is used, which makes reading the code and adding or removing options easier.
Re:Why I prefer objects over switch statements by georgeecollins on Friday February 22, 2019 @03:05PM (#19228649)
And the problem with switch in example is solved with a set of brackets. Why is that so bad? That code with brackets would be clear.
Re:Why I prefer objects over switch statements by ezekg on Saturday February 23, 2019 @12:19AM (#19231816)
It always surprises me how few people use brackets on switch statements when the situation calls for one.
Re:Why I prefer objects over switch statements by s_tec on Friday February 22, 2019 @01:43PM (#19227870)
Plus, you can solve all the issues the article points out using linting tools like ESLint. Rules like no-case-declarations, no-duplicate-case, and no-fallthrough already exist for this exact purpose.
Re:Why I prefer objects over switch statements by Scooty on Friday February 22, 2019 @12:33PM (#19227184)
> another commenter ...commented that performance doesn't matter - they are wrong, a switch can be nested in a hot loop ran millions of times and they do matter

I'm curious how often you find yourself dealing with loops that run millions of times? I think the majority of loops I've written don't need to deal with millions of iterations; most of them probably only rarely break 1000 iterations, and I know for sure that a lot of them can't exceed 100 iterations because of limits in the data.

Seems to me that using a switch over another structure for performance at the expense of readability or maintainability is an example of premature optimization unless you're positive the condition is going to be in a hot loop.

Re:Why I prefer objects over switch statements by flavoie on Friday February 22, 2019 @12:47PM (#19227333)
> Seems to me that using a switch over another structure for performance at the expense of readability or maintainability

But is not more readable or even more maintainable.

Plus there is absolutely no optimization involved, it's just another way of expressing it.

Re:Why I prefer objects over switch statements by Scooty on Friday March 01, 2019 @05:16PM (#19285874)
I was replying to a comment about the performance implications. If you decide on one method over another for performance reasons, I think it's an optimization.

> But is not more readable or even more maintainable.

Both are a matter of opinion and depend on the specific use-case.

Re:Why I prefer objects over switch statements by chrisseaton on Friday February 22, 2019 @12:46PM (#19227319)
> I'm curious how often you find yourself dealing with loops that run millions of times? I think the majority of loops I've written don't need to deal with millions of iterations

It's trivial to come up with 80s-level counter-examples to this.

A megapixel image, for example, is tiny.

Re:Why I prefer objects over switch statements by Scooty on Friday March 01, 2019 @05:28PM (#19285966)
It's also trivial to come up with countless "80s-level" examples that never iterate more than 100 times.

Iterating over a megapixel image isn't a common scenario unless you're processing a lot of large images. Obviously you should optimize hot code paths.

Re:Why I prefer objects over switch statements by vardump on Friday February 22, 2019 @12:47PM (#19227330)
Uh, emulation and scripting language byte code engines? State machines? Filtering?

There are plenty of reasons to iterate a switch statement, even much more than millions of times.

Re:Why I prefer objects over switch statements by Scooty on Friday March 01, 2019 @05:36PM (#19286006)
> emulation and scripting language byte code engines

You get that these are outliers right? The majority of software doesn't need to concern itself with these problems. They're examples of software that deals with analyzing and running other software.

I'm not sure why I'm bothering to respond to these comments. This whole discussion has apparently been system developers telling app developers they need to start micro-optimizing their cold loops because "what if your user clicks the button 12 million times in under a minute".

Re:Why I prefer objects over switch statements by mrmuagi on Friday February 22, 2019 @07:22PM (#19230518)
It's actually a big issue in any performance critical regions of code. I've come across this in both the network stack and the file system (user space and kernel).

Switches can sometimes be optimised away into O(1) using clever static compile time tricks, but if you rely on jump indirection you get branch misdirection penalties, or even worse for a ladder of if's, you are doing O(N) work (where N is number of cases).

Re:Why I prefer objects over switch statements by Scooty on Friday March 01, 2019 @05:55PM (#19286114)
Seems like the key is "performance critical regions of code". Yeah optimize code that is performance critical. Don't optimize the other 99%.
Re:Why I prefer objects over switch statements by mrmuagi on Monday March 04, 2019 @05:07PM (#19306066)
I agree with you, yeah. The problem is sometimes you have to go back to old code and optimise it, because today's performance expectations are higher than yesterdays -- whether because hardware has become more powerful or software is being pushed to its limits. So I'm a bit biased, thinking, "If only this was optimised day 1", but truthfully, recognising the requirements and reacting to the performance needs as they arise can be less wasteful than having ironclad performance requirements that won't be met or needed to be met.
Re:Why I prefer objects over switch statements by sacado2 on Friday February 22, 2019 @03:48PM (#19228966)
Anything with successive iterations / optimization phases, like simulation or even simple machine learning.
Re:Why I prefer objects over switch statements by Scooty on Friday March 01, 2019 @05:41PM (#19286047)
That's why I said "majority". Obviously you should optimize code that is run frequently. I could be wrong, but last time I checked most applications don't involve even "simple machine learning" and when they do it's in a library or service that abstracts those concerns away.
Re:Why I prefer objects over switch statements by gameswithgo on Friday February 22, 2019 @12:43PM (#19227275)
moderately sized database, pixels on a screen
Re:Why I prefer objects over switch statements by Scooty on Friday March 01, 2019 @05:51PM (#19286095)
Both of these seem like cases where you would know you're in a hot loop. I wasn't really clear in my comment that of course you should optimize loops that you know get run millions of times. I was saying: pick your tools based on the context of the code you're writing. Most simple applications involve tens or hundreds of loops that rarely iterate over more than a few values and don't get run more than once every few seconds.
Re:Why I prefer objects over switch statements by zachrose on Friday February 22, 2019 @12:48PM (#19227337)
single-page web app doing n times the amount of work it should be doing because components are synced over an event bus with bindings set up wrong in a way that nobody has bothered to debug