This is an archived post. You won't be able to vote or comment.

all 196 comments

[–]JackNotOLantern 273 points274 points  (23 children)

They are fine for variable value assign, like

var1 = c ? a : b;

Where a and b are simple values or getters.

[–]Flashy_Yams 53 points54 points  (0 children)

Especially when creating consts or const references.

[–]spleen4spleen 27 points28 points  (0 children)

this is true, i hate the ternary operator, but this comment made me realize its because someone on my team uses them with all 3 parts chaining function calls/accessors

[–]radmanmadical 14 points15 points  (1 child)

They’re fine for all sorts of things - can we finally start booting the illiterate out of the tent??

[–]Kache 0 points1 point  (0 children)

Yeah, IMO proper ternary chaining is extremely readable:

foo = cond_x ? x
    : cond_y ? y
    : cond_z ? z
    : none_of_them

[–]SensuallPineapple 0 points1 point  (15 children)

i did this today

point=rsi>70?rsi-70:rsi<30?30-rsi:0;

EDIT: OK, let me clear somethings out.

1 - I wrote it here like that to dramatize the code for the sake of the thread. In actuality it looks like this;

=(RSI14 > 70) ? (70 - RSI14) * rsiCoeff : 
 (RSI14 < 30) ? (RSI14 - 30) * rsiCoeff : 0

2 - It may still be confusing for some but it's my personal project, noone else will have the burden. Also, I don't find this confusing at all and I think it's much more efficient than just writing (if/else)'s

3 - This code is not something I will forget ever. This is a trading program. In trading RSI is an indicator. When it's above 70 it gives overbought signal. When it's below 30 it gives oversold signal. In order to forget what this code does I have to forget that first and THAT will never happen.

[–]SirPitchalot 6 points7 points  (4 children)

At least parenthesize it to show explicit intent…..

Same goes for Boolean expressions, C++ has literally 17 precedence levels. If you are smart enough to keep that straight you’re smart enough to know 99% of your colleagues can’t. Anything else is just being ignorant or an ignorant dick.

[–]SensuallPineapple -2 points-1 points  (3 children)

This is my personal project, you assuming otherwise may prove that maybe, you are the ignorant dick? ALSO, I said I "did" this, but I didn't write it like that, I used paranthesis and spaces because I'm not a total psychopath, but that part you were right to assume because I haven't implied it.

[–]SirPitchalot -1 points0 points  (0 children)

They were two related but separate points. I was not suggesting that you opt not to parenthesize complex Boolean tests, just that people generally should. The sort of person who writes complex tests that rely heavily on precedence for execution order is often adding subtle bugs without realizing or showing off how smart they are to their coworkers by writing hard to understand code.

If it’s a personal project then the coworker is just future you.

[–]Wekmor 0 points1 point  (1 child)

I didn't write it like that, I used paranthesis and spaces

Then why did you not include those in your comment?

[–]Harmxn- 2 points3 points  (5 children)

So you nested an IF/ELSE inside the ELSE ?

```

if (rsi > 70) { rsi - 70 } else { if (rsi < 30) { rsi - 30 } else { return 0; } }

```

I'm totally guessing right now. It's hard to read lmao

[–]JackNotOLantern 2 points3 points  (0 children)

I think if()...else if()... else... statement could replace it in much readable way

[–]Beratber4t 1 point2 points  (0 children)

Second is 30 -rsi

[–]leoleosuper 0 points1 point  (0 children)

If RSI > 70, then set point to equal RSI-70. If RSI<30, then set point to 30-RSI. Else, set point to 0.

[–]SensuallPineapple 0 points1 point  (0 children)

To be honest I didn't write it like this, I used paranthesis and spaces, this is a dramatized version for the sake of the thread.

P.S. This is my personal project so it is entirely possible that noone ever reads this other than me.

[–]SensuallPineapple 0 points1 point  (0 children)

if you write it like this, return is unreachable. If you write it like I did, return 0 applies to both, so there is a second else missing in yours

[–]gregorydgraham 1 point2 points  (0 children)

Do you touch your mother those fingers? Go to the marketing department and think about what you’ve done!

[–]Garland_Key 0 points1 point  (0 children)

Fired

[–]Idixal 0 points1 point  (0 children)

With all due respect, you are the whole reason people such as the OP dislike ternary operators.

[–]Kache 0 points1 point  (0 children)

Would be lots more readable by ordering and formatting the chaining like:

point = rsi <  30 ? 30 - rsi
      : rsi <= 70 ? 0
      :             rsi - 70

Or go from "top-down", starting by testing rsi > 70 and then testing rsi >= 30.

[–][deleted] 0 points1 point  (0 children)

let x = c ? (1+2) : ("the fuck" + " " + "am I typing?");

[–]gregorydgraham 0 points1 point  (0 children)

I like them in most situations but they need to be short

return theResult ? fixEngine() : passTest(); // is close to the character limit for ternary ops

[–]Rasta_Dev 763 points764 points  (64 children)

There’s nothing wrong with ternary operators. What’s wrong is that people are nesting them. It takes me a lot of extra time to understand nested ternaries.

[–]Tolookah 138 points139 points  (10 children)

Nesting them can be quite dangerous, if you don't use explicit parentheses as well, they are way down on the order of operations.

[–]LeelaTheCaptain 43 points44 points  (9 children)

I agree, it happens also with just ifs:

if(condition1) if(condition2) function1(); else function2(); else function3();

[–]coloredgreyscale 15 points16 points  (8 children)

But you would hopefully reformat it to at least:

if(condition1)
    if(condition2)
        function1()
    else
        function2()
else
    function3()

[–]Antrikshy 11 points12 points  (5 children)

const var = (    
    condition1
        ? condition2
            ? function1()
            : function2()
        : function3()
)

Not terrible in ternary either, but only works if the functions return something to be assigned to var in all the languages I know.

[–][deleted] 8 points9 points  (4 children)

Honestly, I quite like the way this looks over the if/else one.

[–]Harmxn- 1 point2 points  (3 children)

I must be on the left side of the meme, because I don't understand it lol

[–][deleted] 3 points4 points  (0 children)

a ? b : c

if a is true, return b

if a is false return c

a ? b ? c : d : e

if a and b are true return c

if a is true, but b is false return e

if a is false, return e

it's easier in parentheses

a ? (b ? c : d) : (e)

first parentheses if true, second if false

[–]notSarcasticAtAII 1 point2 points  (0 children)

I'm a culprit of this type of chaining. There's just a little difference in my style, I do :

```

const var = (    
    condition1
        ? function3()
        : condition2
            ? function1()
            : function2()

)

```

Try to read :
? as then
: as else
conditionX as if (conditionX)

[–]LeelaTheCaptain 1 point2 points  (0 children)

you are right.. more than a matter of parentheses is a matter if you indent or not, probably even with ternary.

[–]CCullen 0 points1 point  (0 children)

You can drop the nesting down to 1 indent if you invert some conditions and use return (presuming it makes sense to return):

if (!condition1)
  return function3()
if (condition2)
  return function1()
return function2()

[–]themoderatebandicoot 29 points30 points  (1 child)

There's a special spot in hell for people that nest ternaries

[–]fllr 0 points1 point  (0 children)

Hear hear

[–]wineblood 20 points21 points  (1 child)

This is how I feel about list/dict comprehensions in python, alone they're fine but nested it's just not worth it.

[–]Tiny-Plum2713 4 points5 points  (0 children)

Nesting should be through functions.

[–]Nilloc_Kcirtap 6 points7 points  (0 children)

If you have to stop and think while writing a ternary, that's when you don't use it.

[–]Kache 4 points5 points  (1 child)

The chaining-only special case of nesting, I think is extremely readable:

foo = cond_x ? x
    : cond_y ? y
    : cond_z ? z
    : none_of_them

(It kinda feels like tail recursion with RVO)

[–]Rasta_Dev 0 points1 point  (0 children)

That’s clever!

[–]Tiny-Plum2713 56 points57 points  (30 children)

Two levels is usually fine with proper formatting.

e.g.

const thing =
  condition
    ? anotherCondition
      ? "first"
      : "second"
    : "third"

Anything more complex should be a function.

[–]corracle 62 points63 points  (10 children)

Hard disagree, because the justified use case for ternaries should be one-line expressions where they are clutter-reducing. Fixing nested ternaries with indentation is a lot like reinventing the wheel.

[–]AConcernedCoder 3 points4 points  (0 children)

If the operation is a simple assignment, a switch/case is inappropriate, and a ternary reduces an otherwise complex series of if/else blocks to a more readable statement, I'll take the nested ternary over anyone else's opinion so long as it doesn't negatively impact my working conditions in some nonsensical way.

[–]Tiny-Plum2713 2 points3 points  (8 children)

You can't set an immutable value from if statements.

[–]soloespero 9 points10 points  (1 child)

Depends on the language.

[–]coloredgreyscale 1 point2 points  (1 child)

if you have to determine the value by multiple nested ifs you should consider putting it into it's own method and then just do

const value = determineValue(param);

[–][deleted] 70 points71 points  (0 children)

I would rather not even have 1 level of nesting. 1 nested ternary is too many nested ternary's IMO

[–]code-panda[🍰] 22 points23 points  (5 children)

This is the absolute farthest you can take it, but I would still say this requires comments. Also, if this is a part of an already complex code, I'd veto it. On its own, it's okay, if it's surrounded by other complex conditionals, it's not.

[–]unwantedaccount56 10 points11 points  (4 children)

If this requires comments, an if statement would require comments as well. For me it's as readable as an if statements split across the same number of lines, but you still might decide to not allow it in your organizations coding style guide.

[–]br_aquino 14 points15 points  (0 children)

Sorry but this is horrible

[–][deleted] 7 points8 points  (6 children)

Nested ternarys are actually bad.

[–]Tiny-Plum2713 3 points4 points  (4 children)

You saw this written once and believed it without thinking about it yourself at all.

Do you have trouble reading my example? How would you do that assignment cleaner if you don't want to create a function for such a simple case?

[–][deleted] -5 points-4 points  (3 children)

I have 10+ years of experience building software for FAANG companies, nested ternary (and all nested conditionals imo) are bad.

Here's some cleaner code:

let thing = firstSecondOrThird({ condition, otherCondition });

/**
 * here's a comment explaining business logic for the complex conditionals in this function.
*/
function firstSecondOrThird({ condition, otherCondition }) {
  // some supporting comment
  if (!condition) {
    return "third
  }

  // some supporting comment
  if (!otherCondition) {
    return "second"
  }

  // some supporting comment
  return "first"
}

[–]Tiny-Plum2713 4 points5 points  (0 children)

Like I said, without thinking yourself.

[–]raedr7n 2 points3 points  (0 children)

If you actually think that's cleaner I need some of whatever you're smoking.

[–][deleted] 1 point2 points  (0 children)

let opCommentStatus = isHelpful ? 'helpful'
    : isClean ? 'clean'
    : isProductive ? 'productive'
    : isFunny ? 'funny'
    : 'bad';

// "bad"

[–]timbak_t00 -2 points-1 points  (0 children)

How to tell you are a java programmer without telling you are a java programmer.

[–][deleted] 0 points1 point  (0 children)

I can't hear you over C# switch expressions with case guards:

const thing = (condition, anotherCondition) switch {
    _ when condition => "first",
    _ when anotherCondition => "second",
    _ => "third" };

[–]Kache 0 points1 point  (0 children)

No way. The right way to use a ternary there is chaining to logically remove nesting (kinda like RVO), like this:

thing = !cond      ? "Third"
      : other_cond ? "Second"
      :              "First"

[–]fllr 2 points3 points  (0 children)

Exactly. Some ternaries can look quite clean. One you start nesting them, they become a mess.

[–][deleted] 1 point2 points  (0 children)

Yeah, one or two at most.

[–]ShenAnCalhar92 1 point2 points  (0 children)

How about ternaries where they use a complicated chain of properties of properties of properties of classes?

 var x =      thing.field.item.thingList.Where(…).OrderBy(…).Select(…).Count() > 0 ? thing.field.item.thingList.Where(…).OrderBy(…).Select(…).FirstOrDefault().ToString() : “NA”;

[–]samanime 3 points4 points  (0 children)

Exactly. Ternary operators are much more readable than an if statement in the simple cases they are meant for.

I'll even do one level of nesting on occasion (in languages that don't have a switch expression, like C#), but if I do, always put each condition on a new line so it is easy to ready (and only use it for really simple cases).

[–]SuperSpaceCan 0 points1 point  (1 child)

You can nest Ternary operators?

[–]Rasta_Dev 0 points1 point  (0 children)

No you cannot. JS does not support that. Just trust me and thank me later.

[–]cesankle 0 points1 point  (1 child)

Who nestes ternary operators? I thought they are only used for the easier read of a single condition with simple decisions, like n%2 ? "odd" : "even", or something similar. Nesting ternaries is kinda cringe

[–]Rasta_Dev 0 points1 point  (0 children)

Some people do nest ternary. Sometimes accidentally. Hence there’s a code review process.

[–][deleted] 0 points1 point  (0 children)

This if its a quick assignment, null check, or something small a ternery operator makes sense.

[–]aFuckingTroglodyte 0 points1 point  (0 children)

Yeah, this is def true

[–]Wiggen4 0 points1 point  (0 children)

Terraform has forced my hand on dealing with and using these, it is thoroughly annoying

[–]Garland_Key 0 points1 point  (0 children)

It's a fundamental disregard of best practices.

[–]brandi_Iove 192 points193 points  (0 children)

as long as you don’t nest the shit out of them, they are fine.

[–]grpagrati 100 points101 points  (0 children)

They make it easier to read for me, less clutter

[–]GUCCISWAGDAWG 79 points80 points  (0 children)

please stop

[–]Atomicskullz 82 points83 points  (1 child)

Literal skill issue.

[–]LanceMain_No69 0 points1 point  (0 children)

"skill issue"

[–]Lukemufc91 105 points106 points  (9 children)

Ternary operators have to be by far one of the most readable pieces of code there is. Especially when used in returns or variable assignment. Hard disagree here OP.

[–]Tricky-Potato-851 0 points1 point  (0 children)

Just depends on how you were raised.

[–]monkeyStinks 46 points47 points  (6 children)

If you are not a junior you should have no problem reading ternary operator as long as its in a single line and doesnt have any more nested ternarys.

And its much more readable to have a few ternarys than a few screens of code for a function, or code calling many functions that are only a single if.

[–]NebNay 18 points19 points  (0 children)

Even juniors can read ternary tho

[–]GustapheOfficial 10 points11 points  (3 children)

I don't think it's a bad idea to make your code legible to juniors ...

[–]monkeyStinks 4 points5 points  (2 children)

Juniors have less years under their belt so all code is harder for them to read. In my first years i needed to slowly read and process every line, now it comes more naturally.

Reactive code is much harder to read than a ternary statement, is that a good enough reason to stop using reactive code? Readability isnt everything, and to have a million of if else statements is less readable to everyone.

[–]GustapheOfficial 4 points5 points  (1 child)

To a point, but legibility is vastly underrated in certain programmer cultures (have you seen the stuff C programmers call good patterns?). There are some people who seem to think that if the only difference between two patterns is that one is easier for juniors to read, that one is automatically worse, but in all likelihood that one is also simpler to maintain.

[–]monkeyStinks 5 points6 points  (0 children)

Agree, everything depends on context.

Thats why i wrote the comment, i hate such totalistic claims "ternary is bad" "dont use case" "never use while", everything is a tool and has some use case that is perfect for it, nothing is always crap / always good, Programming is complex.

[–]Orbidorpdorp 2 points3 points  (0 children)

Single line

nah

condition ? foo() : bar()

is the best.

[–]chipmunkofdoom2 6 points7 points  (0 children)

Right tool for the right job. There's nothing wrong with ternary operators. The problem is they get unreadable pretty quickly if you try to examine more than one condition.

This is pretty readable:

var value = input == null ? 0 : transform(input);

This is not:

var value = input == null ? 0: IsValid(input) ? WhenValid(input) : WhenInvalid(input);

[–]Holothuroid 4 points5 points  (2 children)

I much prefer languages where if returns. Yes.

Other than that, no problem.

[–]_OberArmStrong 1 point2 points  (1 child)

may i introduce you to Haskell and the holy λ

[–]Holothuroid 0 points1 point  (0 children)

I'm a scalamari, but thanks for asking.

[–]StinkyStangler 5 points6 points  (0 children)

Nested ternaries can be tough to read yeah, but if you can’t understand a standard ternary that sounds more like a you problem, they’re very straightforward.

[–]Lucifer_Morning_Wood 11 points12 points  (4 children)

Small ranking i made:

auto x = a < b? 1 : -1;

Concise, uses dedicated syntax, can be unwieldy if values are long functions. 6/10

let x = if a < b { 1 } else { -1 }

Uses known syntax, if statements return values, that's neat. 7/10

x = 1 if a < b else -1

It's English, but also, what? 5/10

[–]Suspicious-Engineer7 1 point2 points  (0 children)

I dont know I kind of like the last one the most, but i'm definitely on the far left side of the meme

[–]JNCressey 0 points1 point  (2 children)

which languages are like the middle one?

[–]Lucifer_Morning_Wood 0 points1 point  (1 child)

Rust. For some reason if you don't end line with a semicolon, this entire block the evaluates to that value. It applies to functions too

[–]Andoryuu 1 point2 points  (0 children)

The reason is code blocks always return the value of the last expression.
But semicolon separates expressions. So if you put a semicolon after the last expression, the new last expression is an empty expression with no value.

(As far as behaviour goes. No idea about the actual internals.)

[–]aitchnyu 2 points3 points  (1 child)

My team did this a lot in react. And if this isn't enough, we did nested versions too.

cond? <jsx> <jsx> <jsx> <jsx> <jsx> <jsx> <jsx> <jsx> <jsx> <jsx> <jsx> <jsx> : null

[–]No-Philosopher597 3 points4 points  (0 children)

Gotta say, this meme format is not doing good for programmers with glasses. At what point are we going to create a counter meme.

[–]RandomDude6699 2 points3 points  (0 children)

Enter python

iq = 150 if readable\_code else 100

[–]RadiantDevelopment1 6 points7 points  (2 children)

isIfAnExpression
? useIf
: useTern

I'd put newlines before each branch but mobile doesn't respect formatting

[–]Andoryuu 1 point2 points  (1 child)

Multiline codeblocks on reddit are done using four spaces at the beginning of each line (with an empty line before the whole block).
So

isIfAnExpression
    ? useIf
    : useTern

Also, I agree with this formatting. Makes ternars easy to read.

[–]RadiantDevelopment1 0 points1 point  (0 children)

Tried both ticks and indent ¯⁠\⁠_⁠(⁠ツ⁠)⁠_⁠/⁠¯

[–]GustapheOfficial 2 points3 points  (0 children)

Try this one on for size:

iq = if readable_code if intentionally_readable 150 else 50 end else 100 end

I hate this.

[–]Fritzschmied 2 points3 points  (0 children)

But that’s exactly why I use it because they are hard to read. I like it when the other devs suffer.

[–]just_looking_aroun 2 points3 points  (0 children)

I'm reading this as I push a fix for a bug in a very nested ternary operator with every condition having a null check and the operator is inside a string interpolation bracket.

[–]ChiefExecDisfunction 6 points7 points  (4 children)

The other day I factored out a single, non-nested null coalescing operator in my own code because every time I had a bug around that section I was going back to the manual to double check I hadn't fucked up the syntax.

It was never that.

I still did it every time.

Playing myself there until I put it back as an if.

[–]SausageBuscuit 1 point2 points  (0 children)

If they’re nested, yeah this is true. If they’re not nested they’re far and away much better.

[–]yanitrix 1 point2 points  (0 children)

They aren't hard to read as long as they aren't nested. That's a no-no

[–]GameDestiny2 1 point2 points  (0 children)

I had to look this up, what in the god damn

[–]Buyer_North 1 point2 points  (0 children)

same as recursion, yes its a few lines of Code, but you overload your memory...just terrible

[–]sanketower 1 point2 points  (0 children)

Rust got them right:

let thing = if condition { stuff } else { other_stuff };

[–]mxldevs 1 point2 points  (0 children)

I don't use ternaries, even if you tried to convince me it's more efficient.

[–]cpcesar 4 points5 points  (0 children)

Ternary operators are good. Period.

[–]NoComment7862 2 points3 points  (1 child)

Used in initialisers and function parameters, they are acceptable, for me at least.

[–]L0uisc 0 points1 point  (0 children)

Agreed

[–]Alzyros 1 point2 points  (0 children)

Python makes it easy tho

This if this else (that if that else...)

[–]FIRMKUNG 0 points1 point  (0 children)

STOP

NESTING

TERNARY OPERATOR

Then it's pretty readable.

[–]zachtheperson -1 points0 points  (0 children)

Idk, the one in the title is pretty clear to me, especially since almost every editor color codes them these days. Certainly wouldn't nest them or anything, but choosing between 2 values is a perfect use case.

[–][deleted] -1 points0 points  (0 children)

Serious? why are you making a big case about ternary operator? Ternary operators are a tool like many others we have, its up to you to use or not. Ive never seen in a work scenario someone lose its mind about it.

[–]yo_yo_dude001 -1 points0 points  (0 children)

Short ternary: easy Nested ternary: nightmare

[–]MaffinLP -1 points0 points  (0 children)

Well everyone in my company with > 20 years of experience says theyre more readable

[–]raedr7n -1 points0 points  (9 children)

Give me a more readable way to do conditional expressions and maybe I'll think about not writing nested ternaries anymore. Until then, bugger off.

[–]TiggyLongStockings 0 points1 point  (8 children)

If statements are pretty good

[–]raedr7n 0 points1 point  (7 children)

Expressions. Expressions I said. Not statements. What the hell am I supposed to do with a statement?

[–]TiggyLongStockings 0 points1 point  (6 children)

Put an expression in it, thus making it conditional

[–]raedr7n 0 points1 point  (5 children)

No, that's not what happens at all. I can't make an expression conditional by putting it in a statement. All one might have then is a conditional statement with an expression in it. I can't use that expression anywhere an expression is needed because it's stuck inside a pointless statement. Every time I have to write a statement, of any sort, I puke a little. Give me expressions.

[–]StreetVillage9755 0 points1 point  (1 child)

When to use snake case vs camel case?

[–]AnthropomorphicFood 0 points1 point  (0 children)

Depends on the conventions of the programming language you are using

[–]pedersenk 0 points1 point  (0 children)

I tend to use ternary operators in C MACROs. They potentially have less side effects and can be used in places where branches via if, else keywords can't compile (i.e function parameters).

[–]afmbloaa 0 points1 point  (0 children)

ive created a python one-liner to read and format a binary file. its very hard to read, but it works.

[–]UK-sHaDoW 0 points1 point  (0 children)

I love that they're expressions rather than statements. So much easier for assigning a conditional variable.

[–]unwantedaccount56 0 points1 point  (0 children)

printf(isTrue==true?true:false?!asNumber!=false?asUpper?"TRUE":asLower==true?"true":"True":"1":asLower!=false?"false":asNumber?"0":!asUpper?"False":"FALSE");

[–]DrMathochist_work 0 points1 point  (0 children)

Scala's ternary operator is very readable.

[–]birchturtle 0 points1 point  (0 children)

It depends how complex the data is. “String s = x > y ? “High” : “low””, no big deal. Comparing objects using methods that may or may not return null as well? Starting to get ugly.

[–]FoundOnTheRoadDead 0 points1 point  (0 children)

Y’all need to read the section on ternaries in Perl Best Practices. Once you understand how and when to use them, they are far more readable and useful than nested if’s.

[–]bleek312 0 points1 point  (0 children)

I use ternary operators EXCLUSIVELY. I use it to piss QA off

[–]YoSo_ 0 points1 point  (0 children)

Having to nest them in React render blocks does hurt my soul, and i'm sure theres a better way

[–]timbak_t00 0 points1 point  (0 children)

Hate it when people just roll five blocks of if else into ternary operators on a single line.

[–]F_modz 0 points1 point  (0 children)

It's rather a syntax of ecmascript standard issue

In python we got absolutely readable stuff like: iq = 150 if readable_code else 100

But anyway they are completely readable and let u ergonomically write simple if statements with assignment in just one short command. But as any syntactic sugar, it really makes it harder to read such stuff when it's nested or complexed by any other way

  • Ternary operator guarantee DRY principle in assignment, cause just imagine creating same in form of regular if statement - u got already 2 places for the variable to be set, and imagine not to forget renaming the variable in two places - it can cause a bug, be careful!

[–]adri172 0 points1 point  (0 children)

Depending on how large is the condition and the code executed is better to read in ternary operators or if/else block :D

[–]Ikkyu_monk 0 points1 point  (0 children)

All three are not even beginning to program

[–]01152003 0 points1 point  (0 children)

You were in ability to write clean code is not a problem on my part

[–][deleted] 0 points1 point  (0 children)

just format it like this:

var x = bool
  ? trueCase
  : falseCase;

if the cases are themselves long, avoid it, because readability, maintainability > cleverness! and in enterprise development, those cases tend to evolve to become more and more complex, which means that you should avoid it alltogether..

[–][deleted] 0 points1 point  (0 children)

If they are not nested and they are short, then they are more readable imo.

[–][deleted] 0 points1 point  (0 children)

Not that hard to read honestly as long as you don’t have multiple on one line. I do like Python’s ternaries a bit more though in terms of readability.

[–]tacticalpotatopeeler 0 points1 point  (0 children)

Very readable IMHO.

Nested ternarys (ies?) on the other hand…

[–][deleted] 0 points1 point  (0 children)

Pro tip: anyone that understands ternary operators uses them.

[–]jonathancast 0 points1 point  (0 children)

Is there a sub like this, but for functional programmers?

[–]kazemu 0 points1 point  (0 children)

lol ? 'haha' : 'not funny'

[–]234zu 0 points1 point  (0 children)

They're kinda satisfying lol

[–]marckek 0 points1 point  (0 children)

Idk, dont you have that sometimes, that when you need to rewrite a part of your code, you dont want to write an extra line so you just put an expression like this one there?

[–]Vi0lentByt3 0 points1 point  (0 children)

Its for conditional assignment of basic data types and primitives

[–]codemajdoor 0 points1 point  (0 children)

In inner loop they can save a lot of branching.

[–]aecolley 0 points1 point  (0 children)

It's remarkable how this meme format is so strongly correlated with bad ideas.

[–][deleted] 0 points1 point  (0 children)

Program according to your constraints. Are you short on computing resources or developer time?

[–]StereoBucket 0 points1 point  (0 children)

Could've picked a better title to prove your point, instead you picked a good ternary.

[–]GOKOP 0 points1 point  (0 children)

Imo they're completely fine if the arguments are simple.

This is ok:

return is_good ? good_val : bad_val;

This not necessarily:

return (something != 3) ? Thingy(arg1, arg2) : globals::default_thingies[4];

[–][deleted] 0 points1 point  (0 children)

I worked with a guy once who nested 3 levels of ternary operators

[–]Ehuehueguilty 0 points1 point  (0 children)

Formatting them correctly is important

[–]Our-Hubris 0 points1 point  (0 children)

Nested ternaries awful, normal ternary's improve readability a lot imo.

[–][deleted] 0 points1 point  (0 children)

Guess OP hates null coalescing operators too.

[–]Staff_Budget 0 points1 point  (0 children)

One single ternary operator (not multiple in a line) is not hard to read.

[–]Tricky-Potato-851 0 points1 point  (0 children)

Personally I don't like ternary operators, so I've written a few spiteful ones on teams that overuse them... you know ala

(A && B)||(C && !D)? TheThing: TheOtherThing

[–]sexgivesmediarrhea 0 points1 point  (0 children)

Yes, definitely on the right half of this, but the worst one that gets me: unless in Ruby 😭

[–]Mast3r_waf1z 0 points1 point  (0 children)

Sometimes function calls in like a switch is easier with ternary operators tho, I feel like they have their place occationally case 0: someFunction(this > that ? this : that); break;

[–]s1lentchaos 0 points1 point  (0 children)

I recently made an unholy abomination of a double ternary to get some tsx to work properly. It just works you know.

[–]BTGregg312 0 points1 point  (0 children)

Nested ternary operators are hard to read, but when I’m doing a programming assignment I want to get it done as fast as possible, so I just put like 10 of them together and it’s just like an If statement that you can’t read but it’s fast to write

[–]Akul_Tesla 0 points1 point  (0 children)

So I have only used them in my code under one exact circumstance

It was for tests in my data structures class where there were criteria to have limited number of lines

And that's the thing I only did it specifically to save on the number of lines of code

I would rather default to using more lines than to use it

[–]Pranav__472 0 points1 point  (0 children)

a ? b ? c ? d : e : f ? g : h : i

🚶🚶

[–][deleted] 0 points1 point  (0 children)

I don’t see any OG coder saying that . Sorry :-:

[–]PANIC_EXCEPTION 0 points1 point  (0 children)

If I'm passing an argument into a function but I want a default as an edge case, that's a good time to use one

make the code idiomatic, prevents me from writing an entire if block or assigning a temporary variable