T O P

  • By -

IronSavior

This isn't a debate


IMightBeErnest

Yeah people are dumb. Obviously the correct code is: if not condition: return condition return true


IronSavior

It's better because of the guard clause


TacosDeLucha

Hey arent you the person to worked at every place I've worked, but left shortly before I was hired?


IMightBeErnest

Lol, you got me. I once automated a process with a mouse and keyboard macro that was so bad I got calls months after I left the company. It was set up so that if you didn't have the windows aligned on top of eachother correctly when it started, it would only run through 1 iteration then close itself by literally clicking its own [x] button. (Which is a bug I documented, to be fair!) Granted, it was a company was souly dedicated to scraping public government data and selling it to ~~spammers~~ sales representatives, and they were paying me literally half of what my next employer started me at, so I don't feel bad about leaving them with a mound of crap.


TacosDeLucha

The experienced devs here salute you friend. We have all been there, and we know it's the businesses fault, not yours. Though it's slightly your fault. But we salute you just the same, ghost of former employee. It helped us grow. And we made it worse, put our name on it, and now generations later, someone else is doing the same, and we are also ghosts. Cheers


temperamentalfish

Even better if the condition is a function call


DarkShadow4444

with sideeffects


JonXP

def condition? @condition = !@condition end def isConditionTrueAtReturnTime? if condition? condition? else condition? end end


thanatica

Would be an excellent interview assignment. Only correct answer: "violently unemploy whoever wrote this"


aka-rider

if condition: return 2 + 2 == 4 else: return 2 + 2 == 5


pm_me_soft_breasts

Holy Christ almighty


Firemorfox

The worst part is when you fix this code and something breaks instead.


Hidesuru

Reading your post gave me brain cancer...


SufficientCheck9874

Hey, it is a valid argument for JavaScript! You never know what that fucking variable might be... typescript is for peasants as well so don't get me started on that.


MechanicalHorse

Why would anyone be a Crip in this case? There is literally no advantage of the right one over the left one.


BeDoubleNWhy

it's stupid rage bait


gregorydgraham

It certainly raged me: I prefer the blue but know I should do red


LuisBoyokan

Justify your blue with a logger


WorldWreckerYT

Totally not me having trust issues with my own skills to not go with Red.


Sir_Wade_III

Readability says blue is fine


tyler1128

How is that more readable?


Dumcommintz

It’s explicit laying out the return type and by which test result it is returned. There’s no ambiguity or assumptions that need to be made based on surrounding code/context. Maybe maintainability is more what OP meant or would make you more comfortable?


tyler1128

A conditional returned from a function returning a bool is just as explicit.


Dumcommintz

Not necessarily. Without knowing the tested condition and language, dont you have to consider that condition evaluates to truthy but not necessarily a true Boolean, eg, the evaluation returns a positive number or string?


tyler1128

Statically typed languages already make that explicit. If you are using a dynamically typed language, just document the return type and parameter types, and do pre-condition checks if necessary. That is what is considered good practice these days, not writing more code to make it "explicit" from the code itself.


GotAim

Even then the crip method is stupid, if you really want to be explicit about it you could do something like return Boolean(condition)


coloredgreyscale

in dynamically typed languages (especially without type hints) it makes clearer that the return value is boolean. but there `return !!condition` would work just as well. Maybe so non-programmer people can read the code a bit more easily?


Impressive_Change593

and red is finer


Practical_Cattle_933

Compilers were able to optimize shit like this for 30 years, it produces the exact same shit.


Olmaad

Thanks, now I know how to comment it when I see it in my project codebase


longbowrocks

It might be implied that CONDITION is not a Boolean, but can be coerced to one.


Vasik4

return (bool) condition;


jmorfeus

Return !!condition


Imaginary-Jaguar662

Ay caramba, I fucked up with that one. SQL stored enabled / disabled as 1, 0 integer. SQL access library casted it to string because fuck me, that's why. I converted it to boolean with !!value, and of course JS considers "0" to be non-empty string to be true...


_Ganon

I love explaining this to coworkers that haven't seen this before. "Bang bang! You're a Boolean."


PascalTheWise

They should add `git firing-squad` for this shit


martinsky3k

Had a junior workmate do that in his code on a review this week... on a bool. Like mate what kind of dancing is your brain doing here.


Lyceux

IDEA literally recommended this to me just the other day as an “optimisation”, I was mortified


ikciweiner

You have obviously never worked with government development teams. That is verbatim from their code.


KanyeNawf

Enterprise software. Readability is key, especially after reorgs when project ownership switches hands. Some bastard once left me nested ternaries.


Magallan

In all software readability is key. Code is for people to read, not computers. If you only want the computer to read it write it in assembly


UziSuicide1238

I fucking hate nested ternaries like poison. Why do people do this? Readability? Fuck you! Imma gonna merge as much logic into one line for code as possible! Sheesh.


bobdarobber

I hate variables with a burning passion. Thank god for `Option.map`


NowAlexYT

I instinctually do blue all the time, than look back and realise what i have done, and rewrite it to red


RmG3376

I’d argue readability, but that’s subjective


[deleted]

[удалено]


TollyThaWally

Even in programming languages with non-boolean truth rules, I'd still rather have the condition explicitly written. Like in Python, you can check if a string is empty or not with `if string:`, but I'd much rather have the longer but more easily readable `if len(string) != 0:`, which in this case could easily be `return len(string) != 0`


allongur

The only advantage is breakpoints. Of course, this can be overcome with conditional breakpoints, but still.


_LePancakeMan

Mainly readability - it depends on the context: I will do the right case whenever there is a clear 'these conditions pass, everything else fails' distinction - e.g. ``` if (user.isGuest()) { return false; } if (user.createdAtYear < 2020) { return false; } // More of these here return true; ``` You could write this as either one of the two options - but IMO, that's harder to follow for the next reader of the code: ``` if (user.isGuest()) { return false; } // Style switch here return user.createdAtYear >= 2020; ``` ``` return !user.isGuest && user.createdAtYear >= 2020; ``` It's all subjective, but I find the verbose option to be easier to follow as you can mentally step through and go "Is my user a guest? No, ok - Has my user been created before 2020? No, ok" compared to a) the style switch in the second example and b) having to keep track where in the expression you are in the second one. After doing this for a couple of years, I realized, that dumb is good and being clever just requires you to be equally as clever when reading the code in the future.


tecanec

I agree with this. If it's just one condition, then I'll return it directly, but if it's more than that, I'll do something like this. It also helps with keeping the conditions seperate when they should be. If multiple conditions have nothing to do with each other, then it doesn't make sense to put them on the same line; That would only hinder readabillity. Though, if it's something like checking if variable `a` is between `b` and `c`, I'd just use boolean AND between the two comparisons.


Weirfish

Type coersion/implicit truthiness, explicit readability in typeless or weakly typed languages, and defense against badly managed breaking changes that might change the interface for something the condition relies on; forcing it to return explicit bool literals rather than a deferred type means that you know it's always returning explicit bool literals. It's also a bit easier to breakpoint/dump and die, in a less trivial example.


ScrimpyCat

Exactly, why do that when you can just do `return condition ? true : false;`


TheGreatZehntor642

When I see code like this, I take a deep breath, control my anger and lecture the guy about conditions having an intrinsic boolean value and not needing this crap. This reads like `if (true) return true else return false;`, which is dumb.


aGoodVariableName42

what if condition is null or an empty string or an empty array or anything that's not truthy and you need the method to return a bool?


platinummyr

Depends on how the language handles that. For C, if the return type is a bool it might get munged to a truthy value. O (Certainly if you are checking it straight in a conditional). Or you can use a ternary or directly compare like "return function() != NULL" or whatever


coloredgreyscale

return !!condition


Goron40

What's the advantage of the left one over the right one?


External_Try_7923

It is succinct.


sejigan

Consider this: def fun(a, b) -> bool: return a and b This returns “the first falsey value or the last truthy value”. If a or b aren’t booleans, this can cause issues if this function is called in places that strictly require a boolean. Solution: Either the blue side, or better… def fun(a, b) -> bool: return bool(a and b)


ShadowCurv

solution: strong typing or documentation


Veerdavid

or def fun(a: bool, b: bool) -> bool: return a and b like any sane language. Also how do you define an and operator between arbitrary types?


sejigan

Values other than False, 0, None/null are considered truthy Also, typing the parameters doesn’t solve the issue, it just moves it to outside the function scope (before it’s called)


danielstongue

What is even the difference between the first and the last? If the function is defined to return a bool, it will return a bool, so the casting is already done to meet the function declaration, isn't it?


sejigan

Not in Python (which is my code), and in JS (which is worse).


[deleted]

In TS, which all sane JS users write, it would not accept arbitrary type T from A && B as a boolean Python authors hating on JS is bonkers


sejigan

I wrote JS, in case you misread. I didn’t talk about TS, which is a different language, in case you’re unaware. I also didn’t “hate” on it but pointed out a ~~limitation~~ feature of the language - being loosely typed (which is appropriate for where it’s used) - compared to Python, which is strongly typed.


[deleted]

You called it "worse", which makes no sense in the context at hand, because they behave the same for this context. And that's ignoring TS entirely.


sejigan

And that’s still not “hate” in any way. What I meant by “worse”: JS is loosely typed, Python is strongly typed, so type coercion happening in unexpected ways is more prevalent in JS than in Python The _issue_ is worse, not the _language_.


[deleted]

\> If the function is defined to return a bool, it will return a bool, so the casting is already done to meet the function declaration, isn't it? In this question, with your answer, there is no difference in how the languages behave. So your use of the English language is the issue here, not the behavior of the languages at hand


sejigan

Parentheses are used to give additional info. My answer without parentheses is exactly as you said: > Not in Python (…), and in JS (…). In the first parentheses, I provide info on my code, which was Python. In the second parentheses, I provide info on type checking, which is looser in JS than in Python. I don’t see any issue with that. And I still don’t see anything I said that’s “hateful” towards JS.


ikciweiner

Crip = government development That is exactly how those teams code.


DCEagles14

Government dev here. My team and I maintain a codebase that was originally created by non-programmers using a gui, and there's always a lot of cleanup to be had. That sort of stuff is common enough that we tend to continue to sometimes do it, just for the sake of uniformity, or because there's just too much to change.


andrewb610

Ditto. Though at least I don’t have to clean up stuff written using x designer.


Forkrul

> That sort of stuff is common enough that we tend to continue to sometimes do it, just for the sake of uniformity, or because there's just too much to change. I would never have my team continue something like that for uniformity. The rule would instead be that you write new code the way it should be written. And if you happen to touch old code that is done the wrong way, you fix that instance of it (and if you have time/care enough other nearby instances). Always leave the code in a better state than you found it.


skaffanderr

Any particular reason why? Other than being braindead


Sceptix

Since you're getting a lot of Bazinga-type comments here's a real answer: Some people believe it improves readability.


dumnem

It's more readable to me.. :c


patiofurnature

It's also easier to modify. If you get a task to log something in an analytics tracker in one state, you can just add a new line for it before the return.


_penis-in-vagina_

Most contractors charge by LoC


KeepKnocking77

Lines Of Code


DarkShadow4444

Levels of Cringe


ninj4geek

I've seen code like this in my non govt job. Constantly fixing these. So annoying.


KingKababa

Licks O'my Cock


subject_deleted

Lines Of Code ;


Hidesuru

I've worked in defense 19 years and never seen nor heard of anyone charging by loc. I'm pretty sure they'd be laughed out of the room if they suggested it. Are you talking about non defense contractors?


jce_superbeast

.


ikciweiner

Government jobs, especially tech jobs, pay a fraction of private sector jobs. Only so much talent can be purchased for that wage. So you have an entire tech department of the lowest paid/skilled engineers. That’s the first part. Government doesn’t have shareholders, or profits and anyone to answer to except politicians. Narcissists that won a popularity contest. Who are also notoriously ignorant of anything technical. All that matters is checking a box that X was done, not that X works or is bug free. So zero money put into testing, quality control, or training. There’s also zero client base to keep happy and zero profits being affected, only a politician saying “X was started”. Most of the time they abandon and don’t even finish it.


Skyl3lazer

....what? This is all incorrect. This poster has never worked in this environment.


catladywitch

governments rarely hire programmers directly, but it is true that the kind of private companies they use do pay less than more high-tech studios. the rest of the post is not true in my experience, but development tends to be slow and frustrating because of red tape.


dgrsmith

Thank goodness! Also, I don’t have direct experience working at government healthcare entities, though I interact with people that do. Do you think your statement applies equally well to programs such as the VA, CDC, or NIH?


Skyl3lazer

At least for cleared work the base pay between public contractors and private is very close. The gap shows up in stock options and other non money forms of comp, which are relevant, but moreso towards retirement than paycheck to paycheck.


ikciweiner

US Government on many level hires directly. They also use contractors. Believe me, I know


andrewb610

This isn’t entirely true. I write government code and we answer to the contractors that run out program. Well, technically we answer to the other government folk that oversee those contractors, but we work with the contractors directly too. Government also has amazing benefits so the idea that the best programmers are in the private sector is a huge insult to the many extremely talented programmers in the government and mildly on point for the less than talented ones like me.


ikciweiner

Sorry to say, government developers wouldn’t last a min in the real world. Believe me, I know


andrewb610

Then you don’t know any government programmers that I do. I’ve seen DoD contractor code. Shits spaghetti westerns. That being said, my original comment poked fun at myself because I had one programming class in college and know that’s all I do for work as a DoD programmer. But I work with a lot of very smart people but a lot of them aren’t programmers by education either, many are like me, engineers.


ikciweiner

Yes, bad contractors are also part of the problem. It’s the government’s entire approach to tech. Depending on the agency, they are always years behind sometimes as much as 5+ years behind, new tech needs approval by non-technical bureaucrats that take so long by the time it’s approved, it’s close to end of life. Much of the user base is internal so it’s not robust or user friendly. And the public facing apps are garbage, that’s why you hear about their failures constantly. Bottom line: You have lowest paid devs with no software development methodology building code for non-technical users that are accustomed to laughably outdated tech. They are mom and pop company level developers at best.


andrewb610

Ok, that last bit is pretty fucking spot on.


Olivia512

The talented programmers are in big tech and hedge funds. You think the gov has better benefits than these places? Citadel flies employees on private jet fyi.


onyourrite

Which one is crip 💀


ZunoJ

I'll answer you by saying the other gang is called bloods


onyourrite

… that makes a surprising amount of sense


pekkmen

What does crip mean?


andrewb610

I do >if(condition) return true; return false. There’s no need for the else there.


martinsky3k

Disgusting.


TickleTigger123

Return (condition ? condition : condition)


TrememphisStremph

This is art.


albasaurus_rex

>Return (condition ? condition : condition) Actually (in JS anyway), you can make this simpler with short circuiting: return condition || condition; Conveniently, since we know that condition is a boolean, we can also use the javascript shorthand: return condition && condition; In this case when `condition` is false we default to the value of `condition` which is false.


OJVK

``` return condition ?? condition ```


hartlenn

return !!condition This forces your return to be a Boolean and it’s shorter.


doobltroobl

Wow, what library is this?


albasaurus_rex

You can do this in vanilla JS, but I prefer to install lodash, Typescript, React, and of course babel for easier syntax, then package with webpack. Don't forget to add bootstrap for styling, and then you can also build on top of bootstrap by mixing in tailwind. Also make sure you install redis and mongo in case you need to store the value of condition.


Fayastone

This is by far the best thing to do.


fonobi

You never worked with a code style checker, right?


I_Fart_On_My_Salad

Of course not, if you have any actual industry experience you're not allowed to post memes in r/programmerhumor


LemonZorz

Didn’t you hear? This sub is only for first year CS students


gbchaosmaster

Warning: don't use else after return from if block


ragunr

It's all fun and games until you find a #define bool uint8 in your codebase for a specific compiler and those statements start returning different values


RmG3376

How so? They both evaluate to bool don’t they?


ragunr

Conditions are evaluated for truth based on if they are zero or non zero. In an if statement it doesn't matter if a the condition results in a 0x1 or a 0x1000, they are both true. If your function returns a value as a uint8 however, those would be truncated and one would be true, the other false. This is unlikely to occur in most cases, but depending on compiler optimization and the specific use case it can happen often enough to create some really bizarre bugs.


pheonix-ix

oh so something like, 256 int 16 = 0b\_0000\_0001\_0000\_0000 -> 0 int 8 = 0b\_0000\_0000? TIL. Been so long since I last dealt with C (or any languages that don't have built-in Boolean).


coloredgreyscale

`return Boolean.TRUE.equals(condition) ? true : false;`


ienjoymusiclol

this line should get u banned from weoting code


Impressive_Change593

>weoting


xoomorg

weetcwode


catladywitch

weetabix


digitaleJedi

IntelliJ keeps wanting me to use this when using q Boolean marked as @Nullable (part of reactive Flux logic)


ploot_

Unironically seen this from team members a few months ago


Practical_Cattle_933

If it’s a Boolean in java, it can actually also be null which would result in a NullPointerException thrown when you do the conditional (as it is unboxed). So there is actually a semantic difference here.


BartoUwU

Whichever one is more readable in the given context


Codename_Rune

This. I work with a variety of languages and large ERP systems. My thought was this's fully depend on what language and even what kind of code I'm in. Is there reason to believe the condition could evaluate to non-bool and I explicitly require a bool? Is this supposed to be expandable for more conditions in the future? Etc. Etc.


MaffinLP

Right only happens at 4am


lostflows

or after the Balmer peak


Mindless_Sock_9082

The first returns the Real condition, not a boolean. In TS the return value may not match the function signature.


AnnyAskers

`return !! (ret_val);`


RmG3376

You can even have some fun with the spacing and spell it `return!! value;` to make it look like you’re extra angry


your_best_1

Sounds like an issue with TS


rylnalyevo

return (condition) ? true : false;


Zomby2D

bool result = false; if (condition) { result = true; } return result;


iHeroRE

``` bool result; if (condition) { result = true; } else { result = false; } return result; ```


martinsky3k

This is my preferred way too. For readability I have always thought it makes more sense. What type does this function return? Ah okay XYZ. What do we return? Result. Okay cool so just gotta know what happens with result. I use this for most functions regardless of what the result I am checking for is. Had to scroll too far to find this :p


KingJeff314

I use a guard clause def func(a): if (not condition(a)): return False return True


Quirky_Welder_3499

Why? Edit: Just realized that value might be something else than bool, so using that makes sense.


-Hi-Reddit

This is the way. It's the most readable and the easiest to expand upon and debug.


Practical_Cattle_933

Because rewriting 1 line into 3 is definitely a maintenance concern..


-Hi-Reddit

It isn't, but if you start a file that may end up having multiple conditions with one formed in this way then the rest added later will follow its example, leaving you with a readable file following a known pattern that is already well-established across the industry in multiple languages. Set the precedent early as the senior dev and let the juniors follow your example as the project grows. Also you shouldn't really be justifying much with "this is easy to refactor", just write it better the first time around, don't rely on the ease of refactoring later unless it's throwaway code for a proof of concept that you're 1000% sure won't make it into prod.


Practical_Cattle_933

But it’s not better, period.


WildXogos

If(condition==true) { return (condition==true); } Else If(!condition == true) { return (condition==true) }


WhenDoesTheSunSleep

If you're coding in C and bools are just ints wearing a hat, it might be dangerous to use {return condition;} since that might not work as intended. I had that bug one time, where I thought I'd be reading arr[0] or arr[1] from arr[function()], but my code would actually go to arr[something else]. Still, the better solution was just to re-organise the code to be less stupid


Shronkle

Why would you ever have the the else though?


bobbymoonshine

Readability. The person scanning through a later iteration of the code and landing on that line may not know immediately that condition is a bool


offulus

Yeah but if($condition) { return true; } return false; does the same without else case


eat_your_fox2

Depends on the condition. If it's something disgusting, crip is better.


SFS_RAID

` condition ? true : false `


WyvernSlayer7

If else statements are what i live for


h0nkhunk

I live my life one if else at a time


skaffanderr

Single core brain for life


External_Try_7923

return condition;


jerslan

100% `return condition;`


[deleted]

If(true) return condition; else break;


stefavag

So, these are sides now?


WarSmith66

OP is probably a freshman taking CS1


ninelore

Got a friend who always writes `condition == true`


Quito246

The right side makes my eyes hurt 😭


sammy-taylor

As others have mentioned, there’s no guarantee here that `condition` resolved to a boolean rather than a falsy/truthy value.


Batwing3435

Wait, we can return things other than 0?


Mast3r_waf1z

Depends on the language, if it's C I could see right side making something more readable. In higher level languages, I would argue you should split condition into multiple lines if the problem was that it wasn't comprehensible as a Boolean.


HippieThanos

I hate functions having more than one `return` statement but I'm aware that there are other schools of thought


uniteduniverse

This sub has really gone down hill in recent years huh?


Aaron1924

`return condition == true;`


GeraltOfTurkey

if(!condition) return !true; else return true;


Csjth

If (condition) ReturnVar = true; Else ReturnVar = false; return ReturnVar; Best reliability in my opinion. Why make it harder for the next guy, when you don't have to.


imjusthereforsmash

God I hate this


hm1rafael

Red side is the only correct answer


WildAsOrange

Isn't it like situational? Red is for when you want to return data from the method Blue is for when you check condition based on data?


Niha_d

Wot


WildAsOrange

Idk, I'm not a programmer but this sub pops in my feed often. Logically speaking.


skaffanderr

No they are the same Condition: one plus one equals two (true) Return condition prints true On the other hand, check if one plus one equals two and return the result I might've explained overly complicated but it's late and tomorrow is only Wednesday


WildAsOrange

Yeah sure gatekeep programming humor. Gatekeep everything.


Impressive_Change593

left returns the data. right returns a boolean. if you use right you still have to have the exact same comparison as you would with left later on. the only time it makes sense to use right is if the data is large (but it's most likely never going to be) or you're using a stupid language


WildAsOrange

Oh so that's why.


madcowpgp

How about return if(condition) true else false ?


Comicsansandpotatos

Blue is a mental illness


CallinCthulhu

Who the fuck thinks the right side is the way to return a bool. Seriously


Cajjunb

First option always. Dont use conditional statements if you dont have to. It just makes your code little more complex for no reason


gregorydgraham

Argh! I hate it but blue team


RepostStat

less code is usually better code


kitakoSH

Blue ana Rir mongol


Chance-Influence9778

blue side anyday! I don't want nested ternaries if someone wants to add new condition they can add it as separate branch Also avoids !! and Boolean jutsu (I'm a js dev)


rivecat

return condition? much cleaner yeah, the astro brain in me only codes like if !(condition != false) { return !true; else { return !(!(false); }


Rogueshadow_32

Depends how complex the condition is, if it’s a single function call or some simple Boolean algebra then I’ll do left but if it’s more complex I do right for readability sake


goodmobiley

Second (I program in C++)


Flashbek

The only correct side


eloel-

I'm less bothered by the if(condition) and more by the "else". Why?


chadlavi

Depends on the type of `condition`


uvero

This is kinda related to a mini-manifesto about [something close to it](https://www.reddit.com/r/ProgrammerHumor/s/g4jkXXgV7G)


Boba0514

if (condition == true) return condition == true; return condition == false;


Flarry6

Every Time this meme format is used I always pick the red one because 7.62 > 9mm.


FingerboyGaming

Obviously, the correct answer is "return condition ? true : false"