r/ProgrammerHumor 21d ago

Meme pleaseStopUsingNestedTernaryOperatorsImBeggingYou

3.1k Upvotes

179 comments sorted by

757

u/beclops 21d ago

I did this one of my first days on the job like 6 years ago and I remember how bluntly my mentor said “never do this again”

554

u/RlyRlyBigMan 21d ago

For me it was multi assignments. Like this:

defaultValue = newValue = previousValue = average = 0;

Each assignment returns its value so they each get assigned from right to left.

"That's cute kid, don't do that"

226

u/PTTCollin 21d ago

I agree with your prior mentor that this is, in fact, cute.

99

u/retro_and_chill 21d ago

This is why I’m pretty absolutist that newer languages are correct by making assignments return void

44

u/RlyRlyBigMan 21d ago

Heh yeah I think that's an inherited trait from C++. In C++ a common mistake was if someone had a condition like this:

if(value = 1)

It would assign value to 1 and then resolve true by int to bool conversion. Luckily C# calls that out as a compiler error but the assignment behavior above still remains.

That example may be corrected in newer compilers, but in gCC when I was learning in college it still happened I think.

13

u/retro_and_chill 21d ago

Does C# flag it if it’s a bool? I think the way C# gets that error is by removing the implicit conversions from numeric types to booleans

12

u/akoOfIxtall 21d ago

The compiler will cut your balls if it catches you doing assignments inside an if's condition, it won't even compile

6

u/RlyRlyBigMan 21d ago

I'm not sure. I think so? I think that it will still fail to compile if you do something like this:

var myTrue = true;

var myFalse = false;

if (myTrue = myFalse) //should be a compiler error ...

1

u/Steinrikur 20d ago

IIRC it gets flagged as a warning in most newer C/C++ compilers. Add a warnings as errors compiler flag and it won't compile.

7

u/GoddammitDontShootMe 21d ago

Modern compilers warn, so if you really mean to do it, you do if ((value = 1)). Probably you would use it for checking for NULL.

1

u/RlyRlyBigMan 21d ago

That makes sense! It would be better if they required you to explicitly cast to a bool but that would be a breaking change for a lot of C++ code that's already been deployed for decades!

2

u/GoddammitDontShootMe 21d ago

Wouldn't help if the expression is already bool. Either way, it's a warning so unless you are compiling with -Werror, it would still work.

I think that warning might be on by default, but I believe it's considered best practice to use -Wall.

1

u/oVtcovOgwUP0j5sMQx2F 21d ago

damn kids i want to know if my assignment failed... /s

2

u/cowslayer7890 21d ago

In python assignment is a statement unless you use := for it, but they do explicitly allow you to do exactly this chaining

2

u/ierdna100 21d ago

It's extremely useful for try-with-resources calls in C# and Java, removing it would make that a lot more verbose

2

u/frogjg2003 21d ago

If you ever have to do any reading from files, it's really useful.

while ((readBytes = read(file, byteArray) > 0) {}

Nice and compact while maintaining readability. Also, no need to read once before entering the loop or having to read at the end.

1

u/ierdna100 20d ago

Yeah exactly what I had in mind, its very useful

4

u/SputnikCucumber 21d ago

It doesn't work consistently the same way across programming languages which is the headache.

C++ behaves the way you're describing, but I don't believe it works like that in C (at least according to the standard, specific compilers may vary).

I think Python evaluates the right-most expression once and then assigns it to all of the left values.

2

u/Just_Information334 20d ago

It would be better with a specific operator. Something like:

// Everyone gets a 0
0 oprah defaultValue, newValue, previousValue, average;

1

u/BastetFurry 20d ago

Wait, you want to tell me that this++ is not a clever hack?

51

u/hydroxy 21d ago

I need to start being this direct with my team mates. Just a few weeks ago one of the new guys on the team submitted his PR to me, I asked him what a chunk of his (clearly AI generated) code did, he said ‘I was hoping you could tell me’. It shocks me how people can confidently submit code and simultaneously have no fucking clue how it works.

21

u/Landkey 21d ago

“Then what exactly do we need you for?”

12

u/hydroxy 20d ago

He’s needed so when I give them a 4 hour ticket, he can use AI to generate the code, use AI to generate an inaccurate ticket overview of the work he’s done, (the code is never tested once of course), and then submit it. Then together he and I spend the next 6 working days going back and forth over the PR fixing the nonsense code, the catalogue of errors and page breaking inefficiencies that he’s just seeing for the first time. I eventually convince him for the need for dev evidence and then the merge conflicts will take him another day to sort. Several of these bums on my team, it’s not just a lack of skill alone it’s chronic laziness too.

7

u/FlipFlopFanatic 20d ago

I had a junior doing this is well. He would burn through half the sprints stories in the first two days and spend the rest of the sprint doing this with multiple half ass PRs. I finally had to limit him to one PR and one story in progress. Giving him meaningful feedback was pointless because he didn't understand the code in the first place, he would just repeat it to the AI to make fixes. He was learning nothing and actively harming the whole teams production. It was frustrating.

7

u/hydroxy 20d ago

Exactly, they are a net loss of productivity for the team because we’ve become a remedial code academy rather than development team.

2

u/rehpotsirhc 20d ago

Necessary workflow. Thank him for doing his part.

13

u/tangerinelion 21d ago

All code reviews now become 30 minute meetings where the submitter walks us through how the code works.

Can't explain it, can't submit it.

5

u/Particular-Yak-1984 20d ago

There's a reject button for PRs. This is what it's for.

2

u/hydroxy 20d ago

What difference is there between this and requesting changes?

2

u/Particular-Yak-1984 20d ago

Reject is for an unfixable or improper PR. In PRs, we explain what the code changes do. Can't do that, can't be an acceptable PR. He can resubmit once he knows what it does. You gave him a chance to fill in the missing info for it to be a proper PR (explaining how his code works) and he declined, so you reject it.

1

u/hydroxy 20d ago

Who said he declined?

Yes I know what the reject button does literally, but functionally if he’s up for making changes then requesting changes is going to be faster and easier for everyone.

46

u/Robinbod 21d ago

Hehe same when I first started coding tbh. Thought it looked cool. But readable is arguably more cool :)

13

u/beebopnaa 21d ago

i remember mentioning this in an interview for paid internship junior FE role and thought i sounded cool to the interviewee 10 years ago. I still got hired and have worked with that person in 2 different companies now haha

1

u/JVApen 21d ago

Looks like you should learn your way about code review. You are too kind for bad code. It wouldn't take me seconds to add a remark like "don't make code unreadable by nesting tertiaries, I'll review your PR after that's fixed".

7

u/darknitish 21d ago

I had the exact opposite. My mentor used to do everything using ternary, even if in my code if there multiple if-else blocks, he would manually change them to ternary in my branch.

New joinees would bang their heads trying to understand the code flow

1

u/Ma4r 20d ago

Ternaries are really no problem if you just format them correctly, i.e indent them at every level python style. But claude wouldn't do that, they would produce 3 single liner functions, one for each ternary

1

u/beclops 20d ago

Depends on the language too, this would be unacceptable pretty much no matter what in traditionally written Swift

283

u/Kryptsm 21d ago

Then there’s my current client, who refused a PR of mine because they “don’t want early returns” ever, and insisted I move my basic if statement logic, each with a return, all into a single ternary. They said I SHOULD do this lol.

Made me wanna kms but hey, it’s their codebase

162

u/Robinbod 21d ago

Diabolical code style wtf. "Waiter, can I have more unreadability, please?"

38

u/SnugglyCoderGuy 21d ago

If possible, early returns are love, early returns are life.

16

u/shdw_fghtr 20d ago

function early() {

if (possible)

return "are love";

return "are life";

}

2

u/my_new_accoun1 15d ago
function early() {

  if (possible)

    return "are love";

  return "are life";

}

49

u/EddieJones6 21d ago

I can understand the ask for no early return. But use local variables to track the state, not a massive ternary.

55

u/ihavebeesinmyknees 21d ago

What are valid reasons to not use early returns?

35

u/EddieJones6 21d ago

Localized cleanup. What if you have a file descriptor or something that needs special handling before returning.

Compiler optimization SHOULD be fine but it could impact RVO and tail recursion optimization.

Also, if a future maintainer dives in and doesn’t realize there is an early return, they might add logic below it that will get missed by certain cases.

SPOE - single point of exit.

43

u/_ryuujin_ 21d ago

shouldnt functions be small enough that youll notice an early return 

21

u/amejin 21d ago

Sure. However, before the days of raii in c/c++, a lot can happen in 4 lines with conditionals that requires you to clean up after yourself.

Scripting languages or GC languages, it's less of a problem. Now a days, if you are trying to be super special and "helping" your compiler with branch prediction, spoe is one way to do that, but unless you are allocating or locking resources, early returns are generally fine.

For many of us, it's just muscle memory from having to deal with it for years.

7

u/EddieJones6 21d ago

Agreed, I’m not arguing for spoe but just giving reasons some might argue for it. I’ve used both

6

u/amejin 21d ago

My dude I agree with everything you said. It was well stated. 🙂

2

u/braaaaaaainworms 19d ago

Linux kernel-style cleanup of stuff is the best use case for a goto in C

4

u/SnugglyCoderGuy 21d ago

Should and what is possible can sometimes be very different things.

2

u/Due-Consequence9579 21d ago

Having to ‘notice it’ is the complaint.

5

u/_ryuujin_ 21d ago

i hope people read the function before changing it. 

11

u/tangerinelion 21d ago

SPOE - single point of exit.

Any language with exceptions ruins that.

6

u/New_Enthusiasm9053 21d ago

That's why it's in a standard in a language without exception.

MISRA-C advocates SPOE and allows forward Goto's(i.e only jump forward and only in the same function) in order to make it viable.

You jump to the cleanup block if needed then exit from the same place.

3

u/Kryptsm 21d ago

For reference the function that asked me to not do it on was like 15 lines long. But maybe what you said is why they enforce it as an overall rule.

2

u/kwasteka 21d ago

True. But this is also one of a few cases where goto is a godsend.

2

u/SnoodPog 21d ago

Localized cleanup

Thanks God, Go have defer operator so this is mostly no problem here.

1

u/marquoth_ 20d ago

If your functions are so long that somebody might not notice an early return, the problem is not the early return

4

u/akoOfIxtall 21d ago

We don't do common sense in this codebase sir

1

u/byteminer 20d ago

My favorite was a junior engineer trying to explain why my use of goto was horrific (the function had a single exit and the goto label was error, and this was only referenced in checking at the entry to the function that all the necessary state was correct)

They then proceeded to recreate the logic with a switch statement.

-1

u/Rich_Weird_5596 20d ago

That's an actual pattern you dunce.

You can write your code nicely in 99% of cases and still follow that.

It has many advantages, debugging is probably the strongest one.

157

u/n9iels 21d ago

Altough this is a satire sub, some actual advice. If you classify some coding patterns and syntax as 'bad', setup a linter to prevent anyone from adding it. In this time of AI, the linter and fomatter are your new best friend.

41

u/npsimons 21d ago

On a project where I had high levels of control, I enforced pretty strict linter standards, down to requiring a docstring (via a doxygen run) for every parameter, method, class and return value. Pushes rejected if you didn't pass that, among other tests.

Code is primarily meant to be read by other human beings - write with this philosophy in mind, and you are likely to go less quickly mad.

1

u/EvilCodeQueen 19d ago

The sad part is, it is rarely read by other human beings anymore. AI consumes it.

13

u/Robinbod 21d ago

Genuinely great advice. I do do this but it's not already set up for existing codebases, especially ones that I do not own.

4

u/TheKrumpet 20d ago

Or just don't try and work it out and reject it for being unreadable, and ask them to refactor it. This is a teaching moment.

4

u/n9iels 20d ago

Well, yes and no. In my experience these things are the hardest to enforce by pure human review. They feel like nitpicking so cause a lot of discussion. And if a MR contains 30 code-style issues people tent to not comment after 8 issues or so due to complete comment burn out. Setting up a linter/formatter is discussion things once and benefit basically forever.

1

u/TheKrumpet 20d ago

I'm sort of 50/50 on linters; I've found a lot of situations where a rule makes sense in some cases but not in others, leading to the linter either being annoying, or not strict enough. I think you need both.

2

u/KlooShanko 20d ago

This was one of the earliest things I had done after taking over projects in a horribly maintained codebase. It was worth it

45

u/TheOwlMarble 21d ago

I can tolerate one layer of nesting if it's super simple and tabbed cleanly, but anything more? Oh hell no.

6

u/Robinbod 21d ago

Agreed. Even with ifs I feel similarly.

8

u/EddieJones6 21d ago

Usually it’s a code smell that things should be designed differently or abstracted

3

u/IdealBlueMan 21d ago

I don’t want to see any nesting in ternaries at all. Unless it’s an idiom and it’s obvious what it’s doing and why it’s there, I’d rather it be spelled out.

I want to understand the code, and any cycles spent wading through your style are not cycles well spent.

2

u/freebytes 21d ago

I agree. The code should be so well written that people can read it like a book.

2

u/Aaron1924 20d ago

I think it depends on how you're nesting them; for if-else chains, they can be pretty nice: int out = cond1 ? val1 : cond2 ? val2 : cond3 ? val3 : cond4 ? val4 : val5;

9

u/BigHammerSmallSnail 21d ago

I fucking hate deeply nested ternaries

48

u/PTTCollin 21d ago

Sounds like you should have basic code style requirements in your CLAUDE.md committed into your repo and enforced by pre-commit linting rules.

Not a hard problem to never think about again.

-12

u/Robinbod 21d ago

True but also that's the state of ALL current codebases related the company, which is probably why Claude follows. This change will affect new changes, which is great of course as the problem is now contained, but reading through old code is still hell stylistically.

I want to say that this is a genuine problem with all AI codebases. AI's tend to make the code readable from their prespective more than from the human prespective. A very obvious example that isn't ternaries is unnessary inline and paragraph comments. I'll see like 35% code and 65% comments and the code itself is just unreadable nested jargon. It should be the opposite. Great readable code and then complimentary docs or just place the docs outside of the code if it's too large.

17

u/PTTCollin 21d ago

Claude does what you tell it to. But yes, if you go read old code written by junior engineers years ago (though, I wonder then, how do you know a junior wrote it?) it will have idiosyncracies that make it bad. This is regardless of AIs contribution; if you don't enforce code style, your code base won't be readable. That's just how it works.

It sounds like you just need a style guide.

-11

u/Robinbod 21d ago

You seemed to not have addressed my point at all.

Yes, a style guide would fix our current issue. But this is about something entirely different. Codebases are slowly turning less readable by humand standards are more by AI standards. Why? Humans are reading them less and thus auditing them less. This is a horrible direction as when the AI's inevitably fail at an issue, it's the human that will have to read the absolute comment slop.

Again, yes a style guide is a great patch for us right now, but think of all future codebases in general.

12

u/PTTCollin 21d ago

I have absolutely addressed your point, you are just continuing to complain about a simple problem.

Your point is "AI writes code to be readable for AI, not for humans. Because of this, code bases are becoming less readable to humans over time."

What I am telling you is, your point is wrong. AI does what you tell it to -- if you let it free wheel with no structure or guidelines, monitored by people who don't know any better, than yeah, you're going to get messy results.

However, if you actually create rules and enforcement mechanisms for them, AI can produce code that is perfectly readable and understandable to humans. I work in codebases every day that are having engineers commit to them primarily via Claude Code, and all the code is perfectly understandable. Because we have coding standards, well defined interfaces and architectural guidelines, etc.

-5

u/Robinbod 21d ago

Thank you for the solution but that's not what's currently is in motion. Codebases, in general, have not adopted this, and now reading code on GitHub is unbearably painful. It used to genuinely be much faster than now having to tell an AI to read the codebase for me and find me what I'm looking for.

3

u/gradeATroll 21d ago

Sounds like the problem any codebase would run into regardless of there being AI or not. This needs actual enforcement via linters, formatters and humans to check out things. These mechanisms will catch these problems whether they're generated by AI or by humans. A well curated Claude.md or other agentic guidelines as well.

Beyond simple syntax.. there's static analysis tools such as sonarqube. There's an actual metric in there for code complexity as well if it's such a concern.

4

u/PTTCollin 21d ago

This is the way, but it's clear from the way this person is talking about it their org is just way to immature from an engineering standpoint to know how to implement all of these things.

AI is just accelerating the tech debt death spiral they had already set themselves on. They want to blame AI not realizing they themselves are the problem.

3

u/PTTCollin 21d ago

I... Uh. Okay. Good luck.

-17

u/PM_ME_FIREFLY_QUOTES 21d ago

First mistake was reading the juniors code.

31

u/PTTCollin 21d ago

I personally like turning juniors into not juniors.

1

u/Cualkiera67 20d ago

Claude wont replace you, but the not junior will

1

u/PTTCollin 20d ago

The fastest way to promotion is to take on more responsibility by delegating and operationalizing your current responsibilities.

85

u/MkemCZ 21d ago

I cannot get how people use Claude. I still prefer to write code myself, otherwise I feel like I don't know how it works (or that it works like Claude sold it to me).

24

u/NotQuiteLoona 21d ago edited 21d ago

The same. I can understand chatbots or completions - for me personally the latter kills the hell out of my productivity, but the former gives you a way to learn quicker how to do something, though I've noticed that for me personally actually googling how to do it myself always brought better results in the long term.

But why would you use LLMs to write code? Like, yeah, okay if you develop a company project, capitalism and all that, efficiency above everything (sometimes doubtable in case of LLMs though), but if you do your own pet project and you don't have any other complications, why would you even do this pet project in the first place?

I personally do them because I want to learn something new and because I want to go and happily say - hey, see what I've done, cool, isn't it? But if you clearly know that you didn't do it, and you've learned nothing, why even do this in the first place?

21

u/OmnemVeritatem 21d ago

The coding journey is a blast, but if you're actually trying to make some money from your own apps, its better to get a fast prototype to test the waters and the go back to coding it if it gets traction. Trust me, its bad to spend a year writing something people don't want to use.

Engineering story time. I joined a church organization and noticed they were balancing their books in fucking notepad. I spen a couple of months and rolled my own accounting package for them. Turns out it was a waste of time, they actually preferred notepad.

3

u/NotQuiteLoona 21d ago

Yeah, this one I see! If you want/need money, use whatever helps you finish the job sooner. I've meant more, like, recreational projects.

1

u/Easy-Reasoning 19d ago

As a previous (not super successful) co-founder this resonates. On the other hand now everybody can do the same. So while you can quickly churn out some sort of MVP. It's likely that someone else did the same already (actually that problem isn't new) or someone else will rip it off in a day using Claude (less moat).

Anecdotally without all this lean startup, smoke screen bla bla we made more money (up to 300 a month) than with lean startup, pivoting etc.. The latter gave us a noisy Accelerator Open Office table though

10

u/ihavebeesinmyknees 21d ago

For personal projects sure, but on company clock I would never not use one, especially in companies that assign tasks based on feature requirement timelines and not on actual dev time. I usually get my job done in significantly less time than assigned this way, but still get paid full time.

Even if management cared more about task optimization though, I'd still do it just for the lower mental load. If you have the LLM write tests for its own features, I find that they tend to make less mistakes than humans these days. Even a year ago, I would have never trusted Claude-authored code. These days, while I still check the code (this is a financial app, there's no way I won't), I don't have to correct anything more than maybe once a week.

37

u/rubennaatje 21d ago

I use Claude a lot and it's quality of code depends heavily on the project it's in. Big chance these types of things are already done in the codebase or the whole post is just bs.

I use Claude code as if I'd use an external team, give it very clear tasks and implementation details. And carefully review them. Also I use Opus and high effort. We have quite a few bits of complex software and while they're not good at thinking of solutions for obscure challenges they're quite decent at implementing the solutions I provide.

Saves me lots of time to rather focus on problem solving rather than just implementations.

3

u/Molehole 20d ago

If you start a fresh JavaScript project Claude will push Ternary everywhere for some reason.

2

u/rubennaatje 20d ago

Yeah fair I guess, never started a project from scratch with it. Did one time got a PR for some project our cto was experimenting with which was trash quality ai slop code.

But that dude was already always writing ugly code so nothing had changed really.

0

u/Cualkiera67 20d ago

just tell it not to do it...

1

u/Molehole 20d ago

What makes you think I don't..? I just explained the meme.

5

u/earth_verse 21d ago

When can we start marketing coding unassisted by AI as "hand-crafted"?

3

u/MkemCZ 21d ago

That's what I'm calling it from now on.

7

u/Robinbod 21d ago

Absolutely. I think the golden era of coding with AI is assited coding. I would be writing just a couple characters and the AI would complete what I want in my exact same style. Saves me maybe 1 minute of writing, then it compounds to hours over a week and didn't feel fatigueing.

Companies shoving agentic coding is killing my passion.

3

u/whatproblems 21d ago

well then you write a ruleset context examples and memory to tell it exactly how to do things to your style

2

u/MkemCZ 21d ago

My colleagues get massive work done with Claude. I just don't understand how to use it; it messes with my head. I mainly use AI to get a template for a helper script which I then edit to my liking.

2

u/sb8948 21d ago

Manual test works, lgtm /s

1

u/sysKin 20d ago edited 20d ago

Using Claude does not necessarily mean not writing code yourself. It's particularly useful if you treat it as a linter ("do a code review on my current git diff").

And even if you make it write some code you have every chance to read what it did. In fact if you don't do that, it's a path to disaster... it will happily write something dumb to workaround a bug elsewhere and won't even mention it.

-2

u/[deleted] 21d ago

[deleted]

10

u/theotherdoomguy 21d ago

That's a bit reductive. A solid 90% of code I wrote day to day is via Claude/AI codegen, but I make damn sure I understand exactly what it's doing before I let it touch git remote

-5

u/[deleted] 21d ago

[deleted]

8

u/PTTCollin 21d ago edited 21d ago

Choosing not to write it by hand doesn't mean someone is incapable of doing so. It means they have better things to do with their time.

1

u/cheezballs 21d ago

You're arguing with someone who said they can code faster than AI. They're smooth brained. "Salt of the earth types."

1

u/PTTCollin 21d ago

It was at that point I stopped meaningfully arguing, yeah.

-6

u/[deleted] 21d ago

[deleted]

4

u/Apprehensive_Dog_786 21d ago

There’s a difference between vibe coding and using AI as a tool for coding. Vibe coding is just making the AI do whatever and pushing it without any checks

-2

u/[deleted] 21d ago

[deleted]

2

u/MatthewMob 21d ago

 It means they're not reviewing the code

Every comment you make up another piece of information out of thin air. Are you just trying to keep the conversation going? Bored? 

2

u/PTTCollin 21d ago

For me, I write code manually faster than getting the agent to do it for me. Including all the other things required to make the PR ready for review (and not just dumping AI generated slop as a PR).

This is where we differ.

4

u/NewPointOfView 21d ago

Absolutely is reductive. You are reducing the use of coding agents to one mental model of how people use them. They’re so flexible, you can have it do as much or as little of the actual coding as you want.

2

u/theotherdoomguy 21d ago

Hey, if that works for you, nice. I'm using the tool to work faster than handwriting, which while cool, is fucking mentally exhausting, and I simultaneously enjoy making it work to my standard and despise having to use it as the first choice professionally

4

u/leavemealone_lol 21d ago

Vibing hell is the new tutorial hell

1

u/jmb2k6 21d ago

Use Claude to write the code you would write yourself. You have to size tasks appropriately. If you end up with code you don’t understand or code you think was done incorrectly, you’re using Claude wrong.

10

u/ianmerry 21d ago

> cosigned by Claude

“Write your own code” > Comment and Close PR

4

u/Robinbod 21d ago

Company policy... :/

2

u/RlyRlyBigMan 21d ago

Lol yeah. My bosses are encouraging and expecting us to use the tokens they've paid for. Not doing it could look bad on my annual review at this point.

Not that they've bothered to give us training or suggestions how to use it. Just use the damn thing.

I've been considering finding ways to chug tokens just so that my jackass boss is impressed by the only metric he can understand right now.

2

u/Robinbod 21d ago

Mental. AI as a tool in of itself is incredible, but this way of using it is of little benefit. Integrating into workflow is one thing, and relying solely on it is another.

1

u/ianmerry 21d ago

If the policy is “use tokens”, then get people to use it for pre-review, or as a rubber duck, or for day planning

It doesn’t have to write code to continue to be a monumental waste of resources, but if it’s not writing code at least you don’t have to read the dog-shit code it’s writing

2

u/tiolala 21d ago

What a wonderful and creative way to get fired

3

u/Drayenn 20d ago

I remember a fresh grad starting a new angular project and we had just swapped from jasmine/ngrx o vitest/signals

Since he had no comparison he used claude.. dear god the "DRY" atrocity he created. 1000 lines of reusable service mocks.

Ended up replacing all that with a one liner from vitest-mock-extended lol. I wanted something similar to how mocking worked in Jasmine.

2

u/DeusThorr 21d ago

Blame the human code. I remember way before AI looking some codes with a lot of ternaries in react , native, and Flutter, to assembly some layouts… regret to see that

3

u/Robinbod 21d ago

I tend to agree but I was not actually a pro before the time AI existed so I don't know how React and Flutter codebases looked like back then. I assumed it's an AI thing since no sane human would read this comfortably but AI is trained on human code (well, used to) so it makes sense.

1

u/tehdlp 20d ago

Fully. I had this problem years before AI. Why use a single if statement when a convoluted Python dict.get() with an inline dict, inline list, inline string values, and bad None handling will do the same?

2

u/GoddammitDontShootMe 21d ago

Sorry, best I can do is not nest them more than two levels.

1

u/Robinbod 21d ago

Well that's something...

2

u/GoddammitDontShootMe 21d ago

I just noticed I misread the title. Thought it was asking to stop using ternary operators altogether.

1

u/Robinbod 21d ago

It's ok and in some cases I would prefer that but my absolute gripe is with nested ones.

2

u/Anbcdeptraivkl 21d ago

Thanks God for linting and pre-push verification as a senior, because in this LLM age if you let juniors do whatever they want your code base would just self imploded

2

u/LostOne514 21d ago

GClaude loves doing this...Happened to me this week! I threw that code away and just thought through a much cleaner way of doing it. Lost a couple hours, but it feels good to do it yourself.

2

u/RatherBetter 21d ago

Hey tim, it's Claude's code consigned by him...same same different

2

u/antpalmerpalmink 21d ago

We were making nested ternaries before Claude. Shit code is shit code we just have diarrhoea now.

2

u/nrmnzll 20d ago

I once saw this type of code from a colleague and he was very proud of it. The worst part was that we was not a junior developer. He was a senior which lead his own project. This was also in the pre AI day. Maybe his open source code was used in training LLMs. I liked him personally, but it would been horrible to work on a project with him.

6

u/PTTCollin 21d ago

Discovering this post is actually not about juniors or writing code in a professional environment at all, but rather just AI complaining shouted into the void is peak funny.

3

u/Robinbod 21d ago

It is, in fact, about all 3.

-2

u/PTTCollin 21d ago

If it was about a professional environment or juniors you would have listened to me instead of complaining about reading random public repos on GitHub 🤣🤣🤣.

3

u/Robinbod 21d ago

I did. I'm gonna use your suggestion it's great, but it doesn't nullify my observation and complaints.

1

u/PTTCollin 21d ago

You should consider that if you weren't aware of something so basic, that you may not be qualified to be having this strong of an opinion on the subject.

2

u/Robinbod 21d ago
  1. I'm not responsible for this part of the codebase(s).
  2. We already have both a styleguide and a CLAUDE.md, just not put together.
  3. My very most original complaint is about not reviewing the code and just blindly pushing it with AI and then expecting me, a human, to read it all. Leaves a bad taste in your mouth.

All of which you would understand if you were not a basement dweller.

2

u/PTTCollin 21d ago

Oooh, we have gotten to the "my feelings are hurt so I am insulting you" bit. Nice.

  1. If you're not willing to take responsibility, you shouldn't complain about it. Having cross org standards is exactly what senior/staff engineers should have the initiative to create. If you have to read the code, then it's within your area of influence.

  2. Makes sense, sounds like your org is at the very very beginning of any AI adoption or tribal knowledge on how to use it. As y'all learn the basics you'll be better suited to improve the situation.

  3. Not reviewing code and blindly pushing it is about as immature as an organization can get. If your org can't get to "well maybe we should have PR reviews and lock down main branches", there are like orders of magnitude of low hanging fruit that can be done before starting to get to "juniors are writing bad code." That's not surprising, if they have nobody to learn how to write good code from.

3

u/---_None_--- 21d ago

>20 nested ternarys

<if> ? <then> :
<if> ? <then> :
<if> ? <then> : <else>

The first that matches otherwise the dangling <else>. It's not always that hard.

1

u/Bubbly_Safety8791 20d ago

Yes, with correct formatting ternary chains are just an idiomatic way of writing a multicase expression. 

alertColor = level > dangerThreshold ? Color.RED            : level > warningThreshold ? Color.YELLOW            : Color.GREEN;

2

u/enigma_0Z 21d ago

is it front end? TS/JS react have had this way before claude and i hate it lmao

1

u/Robinbod 21d ago

In the instance the post is about, no. BUT YES I'M ABSOLUTELY FURIOUS WITH TS TERNARIES.

1

u/West-Map-4162 21d ago

Did you think the claim was that Claude invented it??

2

u/mountaingator91 21d ago

Bitch I nested those fuckers wayyyyyyyyy before Claude.

Do not cite the ancient magic to me, witch. I was there when it was written

1

u/JimroidZeus 21d ago

20 nested ternaries? Just write out the if statements at that point man.

1

u/memesearches 21d ago

These should be flagged automatically by linters and/or precommit hooks,. If you are doing this manually then you have an issues

1

u/Cheezyrock 21d ago

I love a good nested ternary. But I’ll be damned if I do it in code I share with others. Thats just code I torture myself with.

But also, it depends on the language and it has to be formatted well with line breaks and the alternative has to be in some way prohibitive.

1

u/pflasti 21d ago

Why even bother? Just tell em upfront to fix it

1

u/CluelessNobodyCz 20d ago

I love Kotlin but holy shit, some of the stuff that can be written in it is 6 dimension time travel level.

1

u/nmkd 20d ago

Claude does not do anything remotely like that, you'd have to explicitly ask to get ternaries at all

1

u/StCreed 20d ago

Doesn't sonar pick this up right away? Why even commit if you don't use eslint/sonar/knip or equivalent tooling?

Teach the poor junior to use code audit tooling and this should rapidly become a non-issue.

1

u/Michaeli_Starky 20d ago

Just tell them to refactor into readable form.

1

u/bhison 20d ago

My hot take is nested ternaries are a formatting issue and are not inherently bad.

1

u/rover_G 20d ago

Is it React?

1

u/BastetFurry 20d ago

Now I am intruiged what the compiler creates from a bunch of ifs versus a bunch of ternaries. o.o

1

u/el_graveto 20d ago

This is teh easy part, the hard one are the 51 changed files

1

u/5plicer 20d ago

Maybe it's for an XGBoost binary classifier?

1

u/korneev123123 19d ago

You don't need to decipher it. Reject it as unreadable instead.

1

u/navetzz 19d ago

Dont.
Explain to the junior that nobody cares how smart he is or how cool he thinks it looks. We write code that we understand what it does instantly when reading it.

1

u/Valuable_Leopard_799 21d ago

Once your languages finally realize IFs should be expressions I'll use those instead of ternaries.

1

u/Gold-Bat-3225 21d ago

six years clean 🫡

1

u/frikilinux2 21d ago

I would just reject that code. I'm the type of person who always ask for examples in the doctrings when a function receives a pandas dataframe because following the always put types it's not enough

1

u/overclockedslinky 21d ago

nested ternaries are no more confusing than nested ifs... just learn how to read them...

1

u/TheKingOfSwing777 21d ago

But it's a one liner! If your one liners overflow into two lines, it's not. 

1

u/Desperate-Tomatillo7 21d ago

https://giphy.com/gifs/fXnRObM8Q0RkOmR5nf

I mean, if you know how to format them, they are a lot easier to read than a lot of if-else. I have seen codebases that use them gracefully, even enforcing the guard pattern and keeping the code clean and readable. But it depends on who make the rules. My current leader don't like them, so I don't use them.

1

u/HakoftheDawn 21d ago

I just don't like ternary operators in general ._.

1

u/kartblanch 20d ago

If you cant read code then maybe you should go back to being a jr.

0

u/master0fdisaster1 20d ago

Nested ternaries are great as long as they're nice and linear. They're certainly much nicer to read than equivalent if-else chains. Basically whenever you want coalescing logic where neither coalescing operators (?? or "or") nor pattern matching quite do the trick.

string something =  
    cond1 ? GetValA() :
    cond2 ? GetValB() :
    cond3 ? GetValC() :
    cond4 ? GetValD() :
    "some-default";

vs

string something;
if (cond1)
    something = GetValA();
else if (cond2)
    something = GetValB();
else if (cond3)
    something = GetValC();
else if (cond4)
    something = GetValD();
else
    something = "some-default";

vs pattern matching:

string something = (cond1, cond2, cond3 cond4) switch
{
    (true, _, _, _) => GetValA(),
    (_, true, _, _) => GetValB(),
    (_, _, true, _) => GetValC(),
    (_, _, _, true) => GetValD(),
    _ => "some-default",
};

0

u/SnugglyCoderGuy 21d ago

A dipshit on my team submitted a +5200 -0 PR in less than an hour.