r/javascript • • May 15 '17

Don't Overcomplicate Javascript #0

https://bits.ristic.io/dont-overcomplicate-javascript-0
35 Upvotes

34 comments sorted by

View all comments

2

u/ArcanisCz May 15 '17

Well, its not abour redux or javascript. Its "magic number" pattern dated back to C language, even assembler (for example here https://www.viva64.com/en/l/0009/).

6

u/freeall May 15 '17

Not really. Just naming a magic number doesn't make it less magical.

setTimeout(foo, 1000)

vs

var oneSecond = 1000;
setTimeout(foo, oneSecond);

vs

var timeToWaitForNetwork = 1000;
setTimeout(foo, timeToWaitForNetwork);

His point in the article is that it just adds more complexity that you now also have a variable named the same thing as a string. And without any real benefit.

5

u/Shaper_pmp May 15 '17

Magic numbers are dangerous because you don't necessarily know why those numbers were chosen, or what role they fulfil, making the code fragile and hard to reason about.

This article is arguing that changing a predefined (and perfectly self-documenting) string to a symbol with exactly the same name is stupid make-work, and that the added "flexibility" it gives you (the ability to have symbols with different names to the underlying string) is just a confusing antipattern that isn't really a benefit at all.

5

u/cpsubrian May 15 '17

Agreed that if you're matching the constant to the string, the benefits are worth evaluating. I've also had cases where they differed in useful ways though. For example your definition might be const LIST = 'myapp:users:list', such that you can just use LIST throughout the file, and import it as LIST, but in logs and development tooling it is more usefully scoped.