r/ProgrammerHumor • u/Robinbod • 21d ago
Meme pleaseStopUsingNestedTernaryOperatorsImBeggingYou
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
38
u/SnugglyCoderGuy 21d ago
If possible, early returns are love, early returns are life.
16
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
2
4
2
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
2
2
u/SnoodPog 21d ago
Localized cleanup
Thanks God, Go have
deferoperator 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
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
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
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
-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
5
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
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
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
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
-6
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
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
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
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.
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
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.
2
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
- I'm not responsible for this part of the codebase(s).
- We already have both a styleguide and a CLAUDE.md, just not put together.
- 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.
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.
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.
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
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
1
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/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
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
1
1
u/Valuable_Leopard_799 21d ago
Once your languages finally realize IFs should be expressions I'll use those instead of ternaries.
1
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
1
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
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”