r/badcode • u/SpeckyYT sadistic • Apr 22 '21
js ternary operators at their maximum potential
2
u/Sp1um Jun 09 '21
Not a JS dev, not sure if the reduce signature is correct
['run', 'fire', 'execute', 'callback'].reduce(null, (acc, k) => acc || cmd[k])2
u/SpeckyYT sadistic Jun 09 '21
I don't think anyone would ever come on this idea, but that works quite well.
.reducetakes as first parameter the function, so you shouldn't add thenull.2
u/Sp1um Jun 09 '21
The null is supposed to be the accumulator initial value
2
u/SpeckyYT sadistic Jun 10 '21
The accumulator's initial value can be optionally set as the second parameter.
43
u/-IoI- Apr 22 '21
My boss hates me using ternary operators - I can see why now.
46
u/EnigmaticHam Apr 23 '21
Ternary statements have a legitimate use - when you have one test condition and always have two branches in your code. But when you've got more than one, just use if else.
1
u/recycle4science Apr 23 '21
Or reconsider your architecture lol
14
Apr 23 '21
[removed] — view removed comment
0
u/recycle4science Apr 23 '21
Lol fair enough. I didn't really register what exactly you were saying, I was talking about more like what the op posted.
22
u/ws-ilazki &{$$_[0]}(@{$$_[1]}); Apr 23 '21
There's really nothing wrong with ternary operators as a concept, they're just if expressions instead of statements, meaning they're just conditionals that return a value. In fact, some languages like OCaml and F# only have if expressions and it works out quite well, though it helps that they can use
if/then/elseinstead of?and:, which is more readable IMO.The real problem is people thinking writing idiotic one-liners is "clever", resulting in unreadable garbage. If they did the same thing but wrote it as a one-line chain of
if (foo) { foo } else if (bar) { bar } else bazit would be just as awful, no ternary operators needed. Similarly, if you added line breaks and indentation the ternary usage wouldn't be quite as bad to read. Like this:cmd.run ? cmd.run : cmd.fire ? cmd.fire : cmd.execute ? cmd.execute : cmd.callback ? cmd.callback : nullThe code still sucks, but at least with breaks and indentation I can actually follow the chain of conditionals.
Sometimes it's the language's fault and it should be blamed for having bad features or poor design, but other times (like this) it really is the programmer's fault and we shouldn't be excusing their mistakes by acting like the language made them do it.
6
u/christian-mann Apr 23 '21
I would probably write that as
cmd.run ? cmd.run : cmd.fire ? cmd.fireEt cetera. But there are better ways, like the null-coalesce operator, metaprogramming tricks, or fixing your architecture so you know what kind of object you're getting.
2
u/ws-ilazki &{$$_[0]}(@{$$_[1]}); Apr 23 '21
I agree, there are definitely better ways to write the code instead of if/else chaining in any form, which is why I said the code still sucks. It's just not the operator's fault, you can split it up and make it readable just fine. I also agree that the example I used for formatting it across multiple lines isn't necessarily ideal (and isn't even what I'd use normally). I just wrote it that way trying to show the similarity to nesting if/else statements when spread out across lines for readability. If I were writing that kind of chained conditional expression for real it would end up similar to what you did, with a slight difference:
foo ? "foo" : bar ? "bar" : baz ? "baz" : "lol"It helps show that the following lines are part of the expression, plus I read
?asthenand:aselse, so writing it that way makes it read similarly to how these sorts of expressions usually get written in languages like OCaml and F# (though you don't see it as often because pattern matching is amazing):if foo then "foo" else if bar then "bar" else if baz then "baz" else "lol"I wish more languages treated if/else keywords as expressions because it's nicer and more consistent than conditional statements. Using
?:instead works but I'm not a fan of abusing symbols to do the same job because the keywords got hijacked for statements. Still, that's not reason enough to demonise the use of conditional expressions just because some people want to abuse them for terrible one-liners.4
u/Nilstrieb Apr 23 '21
The real problem is that many languages thought that control flow statements are a good idea.
2
u/ws-ilazki &{$$_[0]}(@{$$_[1]}); Apr 23 '21
Exactly! Having control flow as statements just forces those languages to either not have control flow expressions or to abuse symbols to reimplement the same control flow as expressions. Which doesn't make sense because you could get the same result with an expression just by ignoring the return value.
I've found I prefer languages where everything is an expression because it gives you more flexibility and power while also being more consistent.
2
u/TheAJGman Apr 23 '21
I use them a lot for things like
return this if flag else None. Don't think simple ones impact readability.1
u/amanj41 Apr 23 '21
Ternary operators are fine and concise in some instances... but I haaaate when devs chain them like this. It’s uncommon enough I always have to reason about the result
44
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Apr 22 '21
Image Transcription: Code
const cmdJson = {
type: cmd.type || 4,
run: cmd.run ? cmd.run : cmd.fire ? cmd.fire : cmd.execute ? cmd.execute : cmd.callback ? cmd.callback : null
}I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
26
10
13
5
u/Major_Fudgemuffin Apr 23 '21
I asked a coworker to make a change in their PR just yesterday because they had a single level of this (ternary operator feeding into another) on a single line.
OP this picture is my nightmare.
7
u/INTO_NIGHT Apr 22 '21
I thought the rule for ternary was have only two things compared not even sure what this would return
23
u/fukitol- Apr 22 '21
The else clause of every ternary operator here is another ternary operator. It'd work, but everyone would hate you and make fun of you for this.
6
u/CrepuscularSoul Apr 22 '21
Basically yeah. I love ternary for simple one line if else stuff, I might let a second nested one slide if it's formatted for readability, but beyond that I'm not approving that PR.
8
u/HattyJetty Apr 22 '21
That's why ternary operators are right-associative in most languages. Unlike... ahem... php
3
3
Apr 23 '21
reminds me of when i was contributing to a project and the tech lead literally told me
If you can write a multi-line thing in a single line, that's better ;)
in my experience, 90% of good maintainable software dev is writing code that takes as little mental overhead for humans to understand.
span multiple lines, tell a story that's very easy to understand. oh and...
DOCBLOCK YA CODE
4
u/EnigmaticHam Apr 23 '21
If you have multiple cases, just use if-else instead of being "clever" by smashing everything into one line.
2
2
u/ososalsosal Apr 23 '21
Honestly there was a niche video processing language based in very esrly JavaScript where the ONLY way to do conditions was ternaries, so that produced some... uh, pretty eye-pleasing code
1
u/fugogugo Apr 23 '21
what does that || 4 does?
3
u/skrtpowbetch Apr 23 '21 edited Apr 23 '21
i might be wrong but i think what that says is the value assigned to type would be cmd.type if it’s truth-y, else 4. not completely sure though
edit: “type” will equal cmd.type if cmd.type is defined, else 44
u/fforde_thinking Apr 23 '21
You were right the first time. If cmd.type == false then it will set "type" to 4
1
u/killersquirel11 Apr 23 '21
This isn't even their maximum potential. I did a group project and discovered a file where my teammate chained 25 ternary statements together (this was in Verilog)
1
1
1
Apr 23 '21
Kinda reminds me of my leap year function https://github.com/Ta180m/Idiot-Code-Golf/blob/main/leap-year/leap.js
1
0
166
u/Koala_King_ Apr 22 '21
Couldn’t you just do
cmd.run || cmd.fire || cmd.execute || cmd.callback? I’m not super familiar with js. Worked with it a bit, but still not great, so please correct me if I’m wrong.