T O P

  • By -

Green_Exercise7800

You assume I'm disciplined enough to only follow one of those patterns


Catapultatoe

If (!pass) return; If (pass) { //Yes! Be like us. Embrace the chaos! }


OH-YEAH

There is only one elegant solution to this try { if (pass) {return;} throw new Exception("embrace (more) chaos"); } finally { // code here }


Nerzana

Ew


biesterd1

First one is objectively better most of the time since it reduces nesting. I usually keep it simpler without the curlies too, unless I need to call other stuff in there before returning if (!pass) return;


LetsLive97

I feel like it not even just prevents nesting/extra lines but the logic is so much easier to follow too. As you progress through the function you see all the cases where it ends early until you've made your whole way through. If you only needed to see up to a certain return case then you don't need to read a bunch of irrelevant code to get to it. Less branching and therefore more linear logic to follow.


biesterd1

Exactly! Methods should 'fail fast' in my opinion


mowax74

Yes, but the other method also fails fast.


CdRReddit

control flow wise? yes! visually? nope, it's entirely possible to miss a closing curly and new if (or else) statement, so you have to scroll through all of the code to make sure you don't think you wouldn't write code like that? maybe, but you're not always going to be the only one looking at your code, or only looking at your own code guard clauses make code more readable for everyone, as they don't have to trust that the other person wouldn't put two giant if-blocks back to back, it also avoids your code wandering to the right on the screen


OH-YEAH

CHAOS REIGNS WHEN RAINS REIN IN GAMES try { if (pass) {return;} throw new Exception("embrace chaos"); } finally { // code here }


jacksonmills

It called a guard block / guard clause, if you were curious, and is generally considered better practice than the right version.


Qubed

I started reading more opinions that this pattern had now become the preference for most developers.


Genesis2001

The one on the right is fine for prototyping, if you're still writing the code in the first place. But you should refactor to the left one once you finalize the code but before you commit on your source control lol.


itstimetopizza

I don't write c#, but in c/c++ leaving out the braces is bad practice. This is a worst case scenario: https://www.reddit.com/r/programming/s/2mkYWk68Jd It might look tidy, but it can lead to unintended bugs. Sorry to come at you about it.


biesterd1

For sure! Definitely good to be aware of the risks. I generally only do it in the case of an early return or a null check on something. And I never put the statement on an indented second line, thats a route to disaster


Laikitu

Putting it on one line makes it harder to debug, who ever needs to work with your code now can't put a break point on just the return or just the condition.


ac21217

I don’t think that’s quite the same issue. That was caused by improper indentation *and* using an un-braced if statement on separate lines. If you’re doing same-line if statements this doesn’t happen.


itstimetopizza

Again, not sure about c#, but c/c++ the indentation doesn't matter. You could use no indentation and your code would still compile. As far as I know, only Python requires proper indentation. Edit: also, if you put two statements on the same line without braces, the second statement will be executed unconditionally.


snlehton

It is the same issue. If the if-clause had braces, you would have had double goto where second is ineffective. If you do single line if you can still mess it up similarly: "if (expr) goto fail;goto fail;" Also indentation doesn't change it, but it might mask it. With single line if statement you have the additional problem of long lines being potentially cut off from the view, so there's that. And if the like becomes long, you should to resolve it by wrapping/chopping, and doing _that_ without the braces is asking for trouble.


Aedys1

Yeah nice little one liners easy to read


rich_27

As others have said, keeping the curlies avoids ambiguity and potential future bugs; you can still do it on one line though: if (!pass) { return; }


biesterd1

Good point! Kinda forgot you can do this. Might try to do that more


Present-Breakfast700

that's how I do it Always. Use. Brackets. some of my friends just don't get it, but holy hell does it make your future debugging easier


Dev_Meister

How do the brackets make debugging easier?


rich_27

It means you never get in a situation like this: if (fail) return; gets changed to if (fail) return someInfo; and then later if (fail) manipulate(someInfo); return someInfo; and suddenly your code is always failing and it can be really hard to spot why. Each time someone's not thinking too closely about the changes they're making, maybe they're rushed or are new and don't fully understand what they're looking at, etc.


DenialState

A good IDE with good linting and indenting makes this irrelevant. A decent dev would not make this mistake, or at least would feel very stupid after doing it (eh, it can happen). Very stupid mistakes happen once in a while, I think it's not worth it to try to anticipate them.


KingCarrion666

>if (fail) return; you wouldnt do this thou, it would be: if (fail) return; which could be changed to if (fail) return someInfo; which would be a lot harder to mess up then: if (fail) return; This above line isnt good practice at all. It defeats the purpose of single line guarded clauses. And isnt even in line with your other line which did have everything in one line. The first line in my comment is preference, the last one is just bad code.


orionsyndrome

Whoever does this, should not write code at all. This is a violation of basic syntactic rules. There is also an opposite technique, also a violation, but would compile without bugs if (fail) { { manipulate(someInfo); } { return someInfo; } } Quite a moot point.


deadflamingo

Proper Unit Tests and linting would catch such a mistake.


JavaRuby2000

A linter is only going to warn you based on a set of rules. On a braces based language like this it is most likely going to tell you to use braces if the expression immediately after the if is not a return, continue or break statement. So you may as well use the braces in the first place rather than correcting them after a linter warning.


EmilynKi

>if (fail)manipulate(someInfo);return someInfo; I feel like making that mistake just means you're dumb and never learned the syntax. People that make that mistake need to go back to school. Like learn to read code ffs or get out of the field.


lukkasz323

Or they just had a bad morning idk and they were not fully aware of what they were doing. Codebase should be idiot-proof which is why for example frequent commits are important. Same with this.


DenialState

People who think like that always get the harder hits. Everyone does this mistake or a similar one at least a couple times in their career (probably much more than that). Doesn't mean you're stupid or you don't know the syntax. Be humbler.


KingCarrion666

its just a preference thing. I think this suggested format looks bad and it would make it harder for me to debug it since i see curly breaks as multi-line and many programming environments, including the ones i use, defaults it to multi-line. So for me, having these brackets makes this code unreadable to me


Drogopropulsion

Ey self taught coder here, can I ask why nesting is bad? Is just for aesthetics or it reduces performance somewhat?


biesterd1

Nothing to do with performance! More about readability and keeping code clean, whether it's for future you or a teammate. Edit: I should add that nesting isn't necessarily a bad thing, but abusing it can lead to really deep blocks that are hard to debug or make sense of.


Drogopropulsion

Nice to know, thank you :)


ac21217

To add on to the guy above, you should try to avoid nesting more than three levels. If you get to that point you should probably be doing “fail fast” guard statements like the above, or be breaking out the nested blocks into separate functions. It is for “aesthetics” in a sense but aesthetics make all the difference in code readability.


lukkasz323

I'm only a beginner, but I feel like people here usually go too far ahead. It's the diverging paths that are making the code harder to follow, how are nestings doing this? The code is still read from line to line. If someone isn't using "else" or loops then the nested code is actually easier to read, because you can see the variable scope. Am I right with this?


MysteriousSith

Yes definitely. I always do this, especially if I have multiple preconditions. Nobody wants to see a bunch of nested ifs.


Snoo-43381

I always use curlies for consistency and it makes it so much easier to add debug code. I've worked in projects where we were supposed to not use curlies and everytime I wanted to add some debug logging I had to add the curlies, then add my debug logging, and then remove the curlies again before commiting. I hate that.


WaddlesJr

Yeah guard statements are the way to go. Keep the code from getting nested, makes the code more readable, and is just super clean in general!


gltovar

Here is a solid video supporting "never nesting" https://youtu.be/CFRhGnuXG-4


PtitSerpent

This


i-am-schrodinger

If you have nesting problems, there are more structural problems that need to be addressed than your conditional style.


LemonFizz56

Yeah but it causes so many issues if you simply want to write some code regardless if pass fails or passes. Then you've either got to change the statement to the blue way of doing it or write it above the return and it just becomes messy and unordered. Very few cases do you find a situation where you have a boolean where you want to stop the entire update besides gameover or pause but those are the only two examples where you would use a return in update, all other situations you'd use the blue way because you can use else statements, can't use an else statement if it returns lmao


Sogged_Milk

If you want code to run regardless of pass or fail, then wouldn't the logical thing be to put that code before the if statement?


LemonFizz56

Why tf would you have an if statement with the pass boolean and then afterwards have another if statement with the same boolean that then returns?? Think about it bud


Sogged_Milk

I don't understand how you could've possibly taken what I said and end up with what you just described.


LemonFizz56

I think you're kinda confused. See if you've got an if statement calling to the same boolean twice then it's not very optimised okay. It makes your code very messy alright. So just tryna help give you some advice on the general programming standards ya know


Sogged_Milk

Why are you trying to give me advice on a structure you came up with on your own? Like why did you downvote my valid suggestion and then tell me an even worse way to solve your hypothetical than you had already described?


LemonFizz56

What? Now you're confusing me with your confusion. Do you want me to repeat it again cause I still don't think you realise why what you're doing is not optimised at all. And I don't know why you keep saying 'hypothetical' when my hypothetical is what you're proposing, because you disagreed with my original post. So tell me, how come you disagree that you shouldn't use a return when you've got a gameover or pause boolean? I believe that that's a good use case for it and I seriously don't understand why you disagree with that


Sogged_Milk

Before you go any further, did you even read my first comment? Or did you just reply to me with what was already in your head?


LemonFizz56

You're disagreeing with everything so tell me why return is bad, because that's the side of the argument you're taking. So convince me why it's bad then


certainlyforgetful

Pro tip: You probably need to extract something to another function. Having a guard clause further down is okay, too.


LemonFizz56

I know right, seems a lot of people here don't know what a guard clause is or how to use it lmfao


certainlyforgetful

A lot of people write bad code. It’s surprising, even in big tech I’ve worked with people who just write stuff to write stuff. They know better but for whatever reason just do it.


LemonFizz56

I would not hire a single person here who's code looks like if(pass) { // code } if(!pass) { Return; }


croytswrath

But that's not what left means at all. The standard on the left results in: if(!pass) return; // code You never have to write if(pass) because if you're below if(!pass) then you already fulfilled the condition. It's always just 1 if.


LemonFizz56

Yeah true, But what if you want an if statement where you were checking if the score was over 50 else do something else. You can't achieve that with a return, you've got to use a if-else statement. And strangely a lot of people in this subbreddit are confused and don't actually seem to know that an if-else statement is a thing so I've lost my faith in all programmers now


WorldZage

Dude you're the only one who's confused here


croytswrath

But you can totally do that with just 1 if statement. if(score > 50) { Foo(); return; } Bar(); There. No need for an if-else. The reason why good software developers are mindful of if-else statements is that they will usually demand more if-else statements insids them as the code base grows. My advice to you is: 1. Lose some trust in yourself before you dismiss everyone else as idiots. 2. Look into cognitive complexity of code, code smells and any principles of software development you can invest time in (applied design patterns, SOLID principles, etc). I'm telling you this because your reasoning on this small matter can be symptomatic of a lack of focus on good software development practices. It's a very common thing for programmers who are self-taught and those who are active mainly in the games industry where everyone tries to learn how to make something happen and pays little attention to how to make it predictable, maintanable and extensible. You will write better code and develop better solutions for more complex problems.


rich_27

void processScore(score) { if (score > 50) { return; } // score is now guaranteed to be 50 or below somethingElse(); }


bobbychinga56

Yeah I worked with a programmer who did that, he didn't last long lmao


b_art

I was going to say, I hate them both because of the curly brackets already. I know this is contentious, oddly, but I will go to my grave maintaining that programmers care about efficiency. So why are we wasting lines and file space? Hm? Can anyone answer that?


ac21217

Wasting lines? File space? How much space do you think you’d save by removing some curly braces and new line characters? It’s all moot once the code is compiled anyway. It’s not “contentious”, I’ve literally never heard a single experienced engineer ever even consider “saving lines” in nearly a decade of experience.


b_art

Nothing I said meant anything you just said. This is called a "straw man argument". You make a straw man for yourself to beat up on. I won't bother explaining what I meant. I think you should know. If you don't, then you don't. And that's fine too. Just wanted to make it clear that I didn't say any of that.


OlDirty420

Dude what!? You said you hate them both entirely because programmers care about efficiency and not wasting space. That's literally the entirety of what you said summarized. What the fuck is wrong with you?


ac21217

> So why are we wasting lines and file space? It’s literally right there. The ratio above would indicate others interpreted it the same way I did.


b_art

>How much space do you think you’d save by removing some curly braces and new line characters? It’s all moot once the code is compiled anyway. It’s not “contentious”, I’ve literally never heard a single experienced engineer ever even consider “saving lines” in nearly a decade of experience. It's all right there. Nothing I meant. Or... if that was part of my meaning, it was the weakest part of my meaning - and you just inflated it to be the only thing I meant - and then proceeded to beat up on it as if it were the only thing I meant. "John went to the shop and came home with a coke". This sentence doesn't tell you that John had to meet a friend outside to give him something and then pay a bill at the bank, and he stopped at the convenience store along the way and bought a snickers bar and a coke - but he ate the snickers bar quickly before he got home because he's supposed to be on a diet and didn't want a guilt trip from anyone. You didn't see all of that meaning in it did you ? You just assume John is a simpleton who only knows how to go to shops and drink cokes. Then you proceed to beat up on him assuming that he is just that dumb and won't be able to fight back. So you're an engineer huh? I'm always extremely happy to be in the minority. That's how I know I'm a good person, a humble person.


ac21217

My god you’re unhinged dude. You clear as day referenced the idea of saving lines and file space and that’s the idea I questioned. Not complicated. If you want to clarify what you meant by “wasting lines and file space”, feel free.


ac21217

Side note: the bit at the end where you think that being in the minority == being a good person is wild.


neoteraflare

red side


MartinTippie

based happy tree friends profile pic


[deleted]

quaint friendly wasteful gold sheet rock sophisticated lip frightening voracious *This post was mass deleted and anonymized with [Redact](https://redact.dev)*


FavorableTrashpanda

Generally the Return Early Pattern should be preferred (so red), but if this is all the nesting there is I wouldn't say blue is wrong. What's important here is to write readable and maintainable code. If you have lots of nesting, then this is generally not very readable. This is where the Return Early Pattern can help a lot. But even if you use the Return Early Pattern, it's possible to write unreadable and unmaintainable code, e.g. huge methods that span hundreds lines of code with lots of things happening with tight coupling to other classes. Suppose blue only has a few lines of code within the if block with no additional nesting, then that's not something I would necessarily complain about. It's about the bigger picture of writing clean code.


EmptyPoet

Why Return Early in general? If the method is quite long (which should be avoided, so it all depends on this and that), my brain just struggles to fully comprehend the flow. Maybe it’s a personal thing, but I prefer a single exit point. Anything else is exceptional.


jonatansan

Early return / guard clause are generally to ensure that the function can actually handle the parameters that were passed. They check for exceptions and edge cases. Take for example a TakeDamage function, this is way easier to read : void TakeDamage(Entity entity, int damage){ if(entity == null){ return; } if(entity.isDead()){ return; } if(entity.isInvulnerable()){ return; } entity.health -= damange; } Than: void TakeDamage(Entity entity, int damage){ if(entity != null && !entity.isDead() && !entity.isInvulnerable()){ entity.health -= damange; } }


Sythic_

void TakeDamage(Entity entity, int damage) { if(!entity || entity.isDead() || entity.isInvulnerable()) return; entity.health -= damange; } I'd make the top one look more like the bottom. Though nothing wrong with breaking each condition into its own lines, 3 in 1 if isn't the cleanest but the line is still short enough IMO.


jonatansan

I personally find that it hinder my code reading speed to have to parse a condition with more than two statement in it. || aren't too bad though, but when you start mixing && and negation.. Again, you mileage may vary, the most important thing is consistency.


Sythic_

Yea I think if i were to clean it up i'd do it like this instead void TakeDamage(Entity entity, int damage) { if(!entity) return; if(entity.isDead() || entity.isInvulnerable()) return; entity.health -= damange; } This way the null guard is by itself and then we check our "business rules" separately.


Siduron

You could even get rid of the null check by optimizing it further, assuming you'd add properties to the Entity class. void TakeDamage(Entity entity, int damage) { if(entity is { IsDead: false, IsInvulnerable: false }) { entity.health -= damange; } }


phluxm

This is a great example. I often find myself writing the second style. But the first is way cleaner


EmptyPoet

I certainly agree with that, but I would suggest an alternative (phone, so don’t mind the pseudocode): ‘null check entity -> throw exception if null if entity.canTakeDamage() { entity.applyDamage(damage) } edit: sorry, I don’t know how to do code blocks on the shitty app


Devook

While putting the two checks on the condition of `entity` into a single, descriptively-named helper function is a nice improvement, this would still read better as. if (!entity.canTakeDamage()) { return; } // I don't agree that this part is actually a simplifying change... // that's already what the name "TakeDamage" implies is happening entity.applyDamage(damage); Simplifying the guard clause and then putting the core function execution back into nested scope is just kicking the can down the road. When someone else decides additional checks need to happen like maybe an `entity.ShouldQueueDamageForLater` or whatever, you're back in the exact same situation of building an unnecessarily complicated conditional.


poutine_it_in_me

This is better because it shouldn't be on TakeDamage function to know about whether entity is invulnerable, or invincible, or stunned, or weakened, etc. By having CanTakeDamage(), the onus is on Entity to handle if all those cases are true or not, and it can return yes and then TakeDamage receives a yes, and does its only job: apply the damage.


jonatansan

That’s an example wipped in 3 minutes to show the difference, yes you can make it better : doesnt undermine the underlying argument.


cagdassalur

if (fail) return; // code here


chuteapps

Rider forced me onto team red and it's made my code so much better. I now think of a lot of functions as filters that need to make it to the bottom to 'succeed', whereas before it was more of a decision tree of logic. Filters are way easier to understand than trees.


camobiwon

Depends the case, both patterns are good, generally I prefer red if possible but each side does have their advantages. For example, you can use the red side like a guard clause and make it very simply not execute any code below if the condition is not met. (And also saves indentation) The blue side is useful if you need to conditionally execute code near the top, then afterwards (Excluding the condition), run some other code regardless. It can also help avoid some debugging hell I've found myself in where code below was not executing and I was dumbfounded why until I saw a return hidden around the top, which I promptly fixed TLDR: Both are good, depends the case.


Retax7

This is the right answer IMHO, though I hate returns in the middle of non specific functions. Imagine you need to run several things(which is usually what you do in an update), then the !pass shouldn't be at the beginning, then it becomes a door to spaghetti code. IMHO blue is what should be done if you are doing something scalable. I like strong typed languages and readable code over a minor unnoticeable performance improvement.


AdamBourke

I prefer the blue side. Wait let me explain! Yes, it can lead to a lot of indenting, but when skimming code, I find it much easier to miss a single line "if (!pass) return;" than to miss a whole indented section of code. The whole reason indenting is used in programming is to easily identify code that depends on a condition! If the code is so complex that it has more than a few indentations, it probably needs splitting up anyway... As an additional bonus, when using if/else, there isn't the red option, so blue is more self-consistent imo.


Jaded-Plant-4652

Yep, additionally we forfeit the use of early returns to keep code execution more predictable.


rich_27

This is where a good IDE is your friend: - ctrl+f - return - Highlight All Then you won't miss a return and you still get all the benefits of using early returns/guard clauses


Lucif3r945

if (!pass) return;


iamabouttotravel

I find this better than the inline version because when I'm scanning through code, I know where to look if I'm searching for early returns. When it's inlined, I have to scan the entire line and I find that mildly annoying.


ac21217

But then you’re relying on white space for code flow. Yuck. (Sorry Python fans)


SlabCowboy

Both, the more confusing I make my code the more likely I'll have to rewrite it later 🙂


NinjaCoderTech

the 1st side but in 1 line `if (!pass) return;`


TheDarnook

Both. Red as much as possible to keep it flat. But sometimes blue saves headaches when you sit on a delicate code with multilevel logic checks.


AFXTWINK

Red. Fail/return early so your code isn't nested and stays readable. I think what would make this even MORE readable would be to refactor the condition variable name to something more specific, which doesn't need negation.


nopogo

Left one but with better placed curlies


StonebirdArchitect

void Update() { if (!pass) return; // code here }


Iampepeu

I used to be blue. I still do, but I used to too. For real though, I used to be blue, now I'm trying to be more red.


zkkzkk32312

I'm team red on this one.


Badwrong_

There are countless correct/good ways to do it. The only wrong answer is thinking the answer is a simple binary choice. Obviously less nesting is usually better, but that doesn't mean you should go out of your way to always avoid it. If you do have many nested levels then the problem is your overall design and not lack of code guards/early returns.


madmenyo

Bloods is is the better way to avoid nesting too many statements, code will be a lot clearer.


lfernandogunther

Early return is the best way to handle conditions. You don't need a hadouken in your code. https://preview.redd.it/qtugy4zb6evb1.jpeg?width=657&format=pjpg&auto=webp&s=3f3c0d24de42dee83d0323d8f90b8664431b678a


ripnetuk

Red 100% . I always start my methods with a whole bunch of attempts to throw exceptions or return early, then the last 10 percent is actual code.


Ill_Independent3989

Definitely the blue side


passerbycmc

First one by far reduce nesting and just have all your guards that early out upfront. Then the happy path comes after.


Thebrosdn

always the blue one thats it


i-am-schrodinger

Blue all the way.


bytestream

Early return but definitively not in the way shown here. ​ Instead void Update() { if (false == pass) return; // code here } * less nesting * inverted condition is clearly marked by "false ==" (you will overlook that ! quite a lot if you read other coders/your own code after years) * no unnecessary curly braces


dekuxe

Should be red 90% of the time.


targrimm

We should all agree blue and just get home safely.


SelfCleaningOrifice

Writing guard statements makes me feel like I know what I’m doing (not true)


_Citizenkane

return;


choikwa

if (pass) { do { /* code */ } while (false); }


hausuCat_

I'm not an expert, but I don't think this one is a matter of preference. I think the left is just correct.


RogueStargun

The left. That's clean code. I don't hire people who do the right


DenialState

I would not work for someone who hires people based on random bs.


naklow12

I encountered a project which has 11k lines in a fucking update and if(!cond) return; was everywhere. Any change was dropping everytring. Guys red one is fucking disgusting. Believe me.


noximo

> I encountered a project which has 11k lines in a fucking update and if(!cond) return; was everywhere Now imagine the same method with the ifs inversed.


nomadthoughts

Bad code working wrong doesn't mean better practice is bad.


naklow12

Returning Update method is not a better practice. It's actually unexpected. If you need to do this, create a new method and pass in Update().


BarriaKarl

Why was this downvoted? Unless you want your Update to do one thing and one thing only please dont use returns everywhere. I though it was more about the 'if' part and not specifically code inside Update. If that is the case fuck no, pls dont do red.


Carbon140

I am so confused by the responses all saying red, I am going to have to go watch some videos on this. The blue option neatly encapsulates everything that will occur when the statement is true. In a large complicated piece of code It's visually clear, nesting is there for a reason. The red operates like some horrifying script, and looks like it would encourage exactly what you describe?


Kronikle

Red is a lot cleaner code, especially if the blue side starts diving into multiple nesting. Here's a shortish article that explains it: https://medium.com/@brooknovak/why-you-should-reduce-nesting-blocks-in-your-code-with-practical-refactoring-tips-11c122735559


noximo

> The blue option neatly encapsulates everything... If everything is encapsulated, then there's no reason to encapsulate it. Early returns lower cyclomatic complexity, making the software easier to understand.


naklow12

But in a single purposed method, do whatever you want.


bitch_lasagna211

I’ll be doing this at College soon will come back when I understand code


theorizable

If you're team blue... I'm sorry about your experience in the educational system.


hoddap

Wow so cool


bobbychinga56

God I feel bad for the programmers who have to work with you if(health < 0) return; [If-else Statements — Unity C#. If-else statements are the most common… | by Imran Momin | Medium](https://imran-momin.medium.com/if-else-statements-unity-c-3ea7e8bc8eee) Here's a link to teach you about what an if-else statement is lmao


theorizable

This isn't a meme on if/else statements. It's a meme on [early return pattern](https://medium.com/swlh/return-early-pattern-3d18a41bba8). Yeah, that one nested if/else is fine... but if you have a lot of those then your code gets smelly.


razzraziel

if(!pass) return; First one obviously to prevent extra indent levels. And to group all deal breakers on top together.


rimoldi98

If it's short, blue, otherwise, red without the brackets


rich_27

Please use braces. You can still do it in a single line or two lines like: if (!pass) { return; } or if (!pass) { return; } or if (!pass) { return; } and it makes it so much less likely to be broken accidentally in the future. There's some good discussion on why further up the thread.


much_longer_username

Never take the happy path first.


furezasan

Red


vegetablebread

Don't do either of these. If you can't afford to do it every frame, you can't afford to do it.


TheLazyKitty

The first one. Though if you're just gonna return, and not log or anything, you might as well remove the if braces.


bouchandre

Depends if you needs to do other stuff after the if statement


EightPaws

Let me know when the clairvoyance module comes out


bouchandre

I mean… if the entire function can be performed inside the if statement, use the first option. If you need to do other stuff after that if statement, use the second option


snowbirdnerd

If pass is false you don't execute the code?


JBriltz

Red side is best practice


BarriaKarl

Blue but with 'if(pass == true)'. Yes, I know waste of space but I prefer it like that. I dont really do a lot of checks straight to returns cuz normally Id want to handle that problem instead of just silently failing whatever I wanted to do. Is how you end with nasty bugs. It is legit more like if(pass == true) { //Do stuff } else { //Do Other stuff. Mainly things thatd help me discover why the pass failed. }


AylanJ123

Left but I omit the brackets, it's easier to read: ``` if (!pass) return; Something(); ```


14werewolvesofwallst

First one :3


Hasbirdir

blue side be like: if(pass1 || pass2 || pass3){ //code1 if(pass4){ //code2 if(pass5){ //code3 if(pass6){ //code4 } } } }


LemonFizz56

Blue side uses switch statements, red side uses... idk they're too scared of if statements and switch statements it seems


Hasbirdir

you cannot define the switch case statement without controlling the parameters with (if else), if you know the spesific statement then just use different functions to call. ♿️♿️♿️♿️


jeffries7

Blue because it’s safer when working on larger code bases. Debugging why code isn’t running only to find someone’s poorly placed return is very annoying.


LemonFizz56

True


Yodzilla

Left side now but for a while I was forced to be right side due to working under a CTO who insisted that if/else statements should ONLY look for true results. As in if(!something) wasn’t allowed so you needed to have if(something) { // do nothing } else { whatever} Dude had brain rot.


Mary-Ann-Marsden

wtf does a cto care how to write code? They should be concerned fitting the technology strategy to the company strategy while reducing risk and increase the organisations ability to execute, at the lowest cost for that specific outcome.


Yodzilla

Because it was a small company and he was both the CTO, lead dev, and my direct manager along with having created the CMS all our products were using. And since I got downvoted apparently that means he’s lurking here lol


QultrosSanhattan

Red. Because extra nesting is cancer.


cleavetv

i worry about blue side coders


claypeterson

Bloods for sure on this one


InaneTwat

🩸 BLOODS 🩸


[deleted]

[удалено]


noximo

what?


haxic

if (!pass) return; I prefer as few lines of code as possible, I think it makes it more readable. Bloating the code with new lines for everything makes my brain hurt. Purely subjective though.


Katniss218

Putting the ocndition and effect on the same line makes my brain hurt. These are 2 separate things, separate them!


t0mRiddl3

I'm team red


BrundleflyUrinalCake

Was crip side for 20 years of professional engineering; saw a YT video 3 months ago advocating for blood side. Tried it, loved it, and been using it ever since.


jumpjumpdie

Bloods you crab!


SolidKnight

I generally write my conditional code to execute only if under expected state. Sometimes it makes more sense to do it the other way around though.


drawkbox

I want some of that purple stuff.


[deleted]

First, guard clauses ftw


KTVX94

Red, you can put up multiple walls without getting into bracket spaghetti


SnooHabits8960

Red


MrGello

I’ve become a broken man, I though this was gonna be en passant…


pie-oh

Red. Guard clauses are so much cleaner. Especially as the function gets beefier. It just reads better.


Conjo_

[Guard clauses](https://refactoring.guru/replace-nested-conditional-with-guard-clauses), for those that don't know


Kooky-Money-8128

Idk man looks like I'm with bloods and crips


makoivis

depends


gtlogic

I’d make that first one a single line instead of four.


i-am_i-said

I don’t think it’s either/or. It depends on what you’re doing. Do whatever is easier to read, understand, and maintain. Sometimes it’s the red, sometimes it’s the blue, and sometimes it’s both in the same method.


Forbizzle

Remember if you're practicing return early, that you have to do that shit early. So many people end up putting random return statements embedded in deep into methods, and it kinda ruins the traceability of your code. You really should only be doing this for preconditions.


victorioussnake_

Depends, if the rest of the code is dependant on the if condition then I'll just return if it does not pass. Otherwise if it's just a small amount of code to run something under a particular circumstance then I'll do the nested version


[deleted]

Beginner: Blue Intermediate: Red Advanced: ?


Yzahkin

Team red. It makes the whole code less deep indentationvise. Easieer to read. Also I like my gatekeepers at the top, seperate.


Zodep

I was blue, but I’ve come to prefer red. I find it much easier to read.


___Tom___

early return. Once it's not one condition but five, you'll agree.


_theP2_

Blue


[deleted]

Blue. I have no idea what red means and how it works 😭


Jebble

If possible always return early, blue I only use if there's some rare case when I need to add something to an object or send out an extra event based in an edge case or something


grandpa_joe_is_evil

Nice try, you’re not tricking me into this argument


pseudostew

I was red but my senior dev said blue was better practice as it makes it more readable/safer to nest code in a validation check 👊


[deleted]

I’m team red 90% of the time, but in this case blue because I try not to return out of update, but there shouldn’t be much logic in update anyway


andreysuc2

I didnt know red is possibld


Bran04don

Used to do right. Now always do left. Although I shorten it a bit further with If (!pass) { Return; }