Escape Nesting Hell - Do This Instead

  Рет қаралды 266,992

James Makes Games

James Makes Games

Күн бұрын

Learn how to improve your if statements in Unity to make them cleaner, more readable and easier to maintain using guard clauses.
SUBSCRIBE
Subscribe for more game dev tips and tutorials: bit.ly/3edJUA5

Пікірлер: 504
@codichor6036
@codichor6036 2 жыл бұрын
Being able to make your code look like a flat list of instructions vs some kind of pyramid shape is really overlooked but it's a total lifesaver when you're hunting bugs.
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
Definitely! It even helps you recognise opportunities to refactor that you might not have spotted if your code was nested
@powerpc6037
@powerpc6037 2 жыл бұрын
It doesn't just look cleaner and easier to find bugs, it's also easier to add extra conditions afterwards without messing with the entire indentation tree and shifting every other condition an extra tab to the right.
@blinking_dodo
@blinking_dodo 2 жыл бұрын
​@@JamesMakesGamesYT i refactored your statement... 🙃 You should really consider getting rid of redundant accolades... (see my contribution somewhere in this comment section.)
@ruslan_yefimov
@ruslan_yefimov 2 жыл бұрын
@@powerpc6037 also you can make lines of code longer
@tofikadigozalov9472
@tofikadigozalov9472 2 жыл бұрын
Its not overlooked by people who hire you tho (: Its overlooked by rookie devs who just started coding and it really slows down their learning by a lot
@Nerdsown
@Nerdsown 2 жыл бұрын
I've always heard this referred to as an "early exit". It is one of the easiest ways to greatly improve readability.
@spythere
@spythere 2 жыл бұрын
Yeah, I also use it on daily basis and call it "guardians" because they guard the rest of code where you can't pass e.g. undefined value or unresolved task. It really makes it easier to read and manage the logic.
@Ishanatmuz
@Ishanatmuz 2 жыл бұрын
I have been using this approach for 5 years now. Everywhere from servers to frontend to Unity. Never knew it was called guard clause.
@udyfrost6380
@udyfrost6380 2 жыл бұрын
Same here man. Never knew the name
@phitc4242
@phitc4242 2 жыл бұрын
I found out about the name once I googled for if it makes any difference or if it was bad practice (I was wondering if the code would get larger when compiled, speed performances, etc...) but now I do it all the time...
@ptidus1
@ptidus1 2 жыл бұрын
Web dev here, I've seen this approach under the name "Early return pattern". Funny to see how good practices propagate even with different names.
@KiemPlant
@KiemPlant 2 жыл бұрын
Me thinking I was going to learn something new (:
@Alche_mist
@Alche_mist 2 жыл бұрын
I knew it as "Early returns". It's quite standard approach in Python for example.
@cappydev
@cappydev 2 жыл бұрын
Beginner programmers, take notes! Readability and structure is king in systems
@dr_birb
@dr_birb 2 жыл бұрын
Maintainability and performance*
@cappydev
@cappydev 2 жыл бұрын
@@dr_birb Of course, it should be structured for maintainability and performance
@mortenbork6249
@mortenbork6249 2 жыл бұрын
@@dr_birb code is for people. Your CPU reads only 1 and 0. Humans read code. Code is for humans. Make your code readable to other humans is the first priority of your code. If no one can follow your code. You will eventually not be able to follow your code. Coders must write readable code. It is the top tier metric. Anything can be fixed that can be understood. Something that cant be understood can't be fixed. And code always changes. It's in the name. "Software" If code never changed. We would just be making hardware.
@dr_birb
@dr_birb 2 жыл бұрын
@@mortenbork6249 holy fuck learn to write like a human. Also no. Code isn't for humans, code is for computer. Humans are paid to read and write the code, even if it isn't easy/simple. Maintainability and performance was is and will be the most important thing in projects that are constantly evolving. Sure, most of the time writing clean and readable and minimalistic (simple) code is also good performance wise and is scalable, but that's not always the case, and that's why it's not the king.
@Dreadnaut2560
@Dreadnaut2560 2 жыл бұрын
@@dr_birb Actually, code is for humans, it just is also for a computer. Most code we write is in a higher-level language that is interpreted through multiple steps into machine language. HLL is literally designed to be easier to write for humans. If humans can't understand the code easily, it makes it very difficult to maintain the code and even make it efficient in the first place. Code acts as a bridge between human ideas and a computer's execution cycle.
@lyons5609
@lyons5609 2 жыл бұрын
This was a game changer for me when I first started writing code like this.
@marzzbar
@marzzbar 2 жыл бұрын
I've beem programming for 10 years, not games, but this is a really good way to explain this. The way I visualise it is like a freeway, with exits. Most traffic goes along the freeway, but if there are certain conditions, they will exit with certain actions as per the criteria.
@hidgik
@hidgik Жыл бұрын
I am not a programmer at all, but I am amazed that I was even able to understand the issue and the elegant solution offered offered to resolve it! Crazy!
@R.B.
@R.B. 2 жыл бұрын
The cautionary note here is that a function shouldn't have multiple returns if it can be avoided. Enter at one point, exit at another. What if there are multiple conditions which must be met for an action? Something which can help is a local boolean flag which can set a condition. In this example you are only writing one thing based on the state, but it might be better to have multiple conditions reported. Having a boolean shouldAttack initially set to true and then setting it to false and falling through the guard instead of returning, you can check all those other conditions as well. Then for the final attack call, put a guard which checks should attack. In this way you've decoupled that logic again but you don't have a bunch of checks which can all drop out of the method. A true guard check is one which is looking for conditions which might break the function, is the parameter passed into the function null, sort of thing. Short and not complicated logic. As a personal style choice, this is the only time I use an if statement on one line and only then if it is very well understood why. Anything more complicated like your example, I'd rather use the flag because it further breaks it up into guard, condition, and (conditional) action.
@Ishanatmuz
@Ishanatmuz 2 жыл бұрын
@Ryan Beesley Care to show an example? Will be easier for us to understand what you mean.
@digdug1431
@digdug1431 2 жыл бұрын
@@Ishanatmuz What Ryan suggested is this: private void Update() { bool shouldAttack = true; if (!Input.GetMouseButtonDown(0)) { shouldAttack = false; } if (IsSprinting()) { shouldAttack = false; } if (IsBlocking()) { shouldAttack = false; } if (IsJumping()) { shouldAttack = false; } if (shouldAttack) { Attack(); } } In this small case there isn't really any difference, but the main advantage of this code is that it is easier to find bugs because all branches pass through the final if statement, allowing you to place a breakpoint there and see what state the code is in right before it exits.
@volfdoesit
@volfdoesit 2 жыл бұрын
@@digdug1431thx mate. I think this might be better approach becouse it doesn't contain those returns which are messing with whole update function if you want to have more than one action.
@Ishanatmuz
@Ishanatmuz 2 жыл бұрын
@@digdug1431 Thanks for the explanation
@augustnasman
@augustnasman 2 жыл бұрын
Guard clauses rely on multiple return statements and that is not bad. It makes alot of sense to return a function right after a condition is met, since you then KNOW what will happen. If you dont return, somewhere else in the code you can mess up the flags making the code hard to debug. Returning is good!
@pchris
@pchris 2 жыл бұрын
It's always nice finding out there's a name for stuff I've been doing for years
@SolironBrightwoode
@SolironBrightwoode 2 жыл бұрын
Concise yet informative! Love seeing videos that don't unnecessarily bloat simple concepts. For those looking for more videos of this nature (code structure and design), search for that and leave out things like Unity and C#. It's general programming advice you're looking for. Which is the same whether you're making a game, website, api... You get it.
@roellemaire1979
@roellemaire1979 2 жыл бұрын
When I was in University the teachers always said to avoid (just dont do it) having multiple return statements in a function, especially if the function has no return value. It is (was maybe) considered bad programming
@skenming
@skenming 2 жыл бұрын
Good or bad is always situational when you think about it. Do whatever fits your needs in practise. In this example, 'return' just act as nothing but 'terminate here' so it is okay in this situatuation.
@wisnoskij
@wisnoskij 2 жыл бұрын
It is really good in this tutorial to show how the simple inversion of the logic completely untangled the flow, but I agree in practice you want to avoid bloating a source file to twice the required line/character amount. Just use else ifs and put the attack in the final else and we can remove half the lines of code in that example.
@Brahvim
@Brahvim 2 жыл бұрын
I have used this concept before, but I neither thought I could make my code clean with it, nor did I know it's name. Thanks!~
@MyGameDevPal
@MyGameDevPal 2 жыл бұрын
Nice thumbnails James! Also I love the way you cut out the empty space, only including relevant clips, most tutorials don’t do that :)
@chosencode5881
@chosencode5881 2 жыл бұрын
Been programming for a few years now, always had an instinct to take advantage of the empty else but I never thought of this. Thank you so much
@Exilum
@Exilum 2 жыл бұрын
It's unlikely I'd use guard clauses for this specific example (at least not in this way), but I do like using it in methods for errors, obvious cases in which you don't need to run what's behind, etc. Makes it more easy to separate things.
@unarei
@unarei 2 жыл бұрын
This seems like a pretty nice use case for them for me - you're attacking only if a set of preconditions are met. I probably wouldn't do it for the mousedown but for all the rest it makes sense
@Exilum
@Exilum 2 жыл бұрын
@@unarei If you have separate methods for each input it makes sense. Because you tend to return, it can't work if you have more than one utility per method.
@unarei
@unarei 2 жыл бұрын
@@Exilum Yeah. I guess if you don't want to split it out, you can put it into an if-else chain instead of whatever mess the original code was in this video
@dorky5256
@dorky5256 2 жыл бұрын
That is actual genius. I've had so many cases where this was a real problem having so many stacking if statements. Great tip
@EnricoDias
@EnricoDias Жыл бұрын
Better yet, use chain of responsability. A list of classes implementing the same interface, each one checking for a specific condition. The method walks the list of classes before performing the action and returns early if any of them fail. That way you just need to add a new entry to the class list when adding a new restriction, leaving the original method untouched.
@pmoneyish6869
@pmoneyish6869 7 ай бұрын
This is interesting. The question I have around this would be how is each condition class getting the data to do the checks?
@JACKHARRINGTON
@JACKHARRINGTON 2 жыл бұрын
This is about the first practical thing that I’ve learned about coding.
@megascan
@megascan 2 жыл бұрын
when you unintentionally already operate like this since you found it neat
@isaackay5887
@isaackay5887 2 жыл бұрын
This video: *_Yandere Simulator dev:_* * nervously sweats and scrolls past *
@XDubio
@XDubio 2 жыл бұрын
I have to maintain code with a lot of these nested condition structure. Thanks for making the world a better place!
@JayadevHaddadi
@JayadevHaddadi 2 жыл бұрын
I have been using this for ages and I love it. It is the first time i know what it is called!! Guard clause !!!:))) 👍😊❤️
@jeroenvanwees3250
@jeroenvanwees3250 2 жыл бұрын
This is great! I have used guards clauses before, but not consciously. From now on I will.
@FunkyAnimations
@FunkyAnimations 2 жыл бұрын
More tutorials like these are NEEDED on KZbin thank you!! I've always looked for things like this and having a video going over it is incredibly helpful
@abner20bushi
@abner20bushi 2 жыл бұрын
That is pure logic. We are so conditioned (pun intended) to check what IS that we do that even when it's more logical to check what IS NOT. Excellent video man.
@javasbot5197
@javasbot5197 2 жыл бұрын
This is a good way! :) IMHO you could improve it with case-switch: removing all those 'if' and using a single 'return' a the end.
@therickestrick383
@therickestrick383 2 жыл бұрын
I was stunned for a moment, why didn't I think of that.. my codes were spaghetti.. And thanks for making it quick!
@Povilaz
@Povilaz 2 жыл бұрын
When I began programing _this_ is how I used to write my code, but over the years I slowly changed into doing the layered method. Idk why that's interesting.
@ethanwobser8776
@ethanwobser8776 2 жыл бұрын
I have heard of something like a clause that can clean up code I didn't know exactly what they were talking about back in the day but now I just started to learn Unity & C++ I kinda understand what is happening
@torikenyon
@torikenyon Жыл бұрын
Remember to EQ your voice! I was watching this on my TV and it triggered the subwoofers to shake the floor due to unneeded sub-bass frequency information that’s not actually part of the sound of your voice. A high pass filter around 100 Hz should do the trick
@JamesMakesGamesYT
@JamesMakesGamesYT Жыл бұрын
Thanks for the tip! Audio is something I've tried to get better at with each video
@TMPfernando
@TMPfernando 2 жыл бұрын
I never thought about using return this way... nice trick.
@Vaaaaadim
@Vaaaaadim 2 жыл бұрын
I am not a game programmer, but I've certainly used this pattern before, didn't know they were called guard clauses. The main places I've used it is in loops in combination with the "continue" statement.
@CrippleX89
@CrippleX89 2 жыл бұрын
In Swift, ‘guard’ is actually a language keyword. It takes a set of conditions and it requires to break out of the block (e.g. return from the method). imho that’s a very nice feature, it makes the core even easier to understand.
@pliniomourao
@pliniomourao 2 жыл бұрын
It is always good to have a reminder of good practices and patterns. thank you for sharing!
@wa1gon
@wa1gon Жыл бұрын
That is a good start. I would also add that all the if should be extracted to a guard method that returns a tuple (bool isAttackable, string message) = CanAttack(..); Methods must only do one thing. This one is doing two: 1. checking to see if you can attack, then if you can then attack. This makes the code much more testable.
@juanpuppinmonteiro
@juanpuppinmonteiro 2 жыл бұрын
Thank you, it will help me a lot! In a kind of way, it's a very obvious solution, but it's one of those that I've never thought about.
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
Glad the video helped!
@mattsponholz8350
@mattsponholz8350 2 жыл бұрын
Early going I used to cringe at this technique but it's honestly a life saver; especially, if you bring someone else on the project.
@DarkryeXII
@DarkryeXII 2 жыл бұрын
Been doing it for years, never knew it's an actual thing lol Great video
@GUMMY_MKII
@GUMMY_MKII 2 жыл бұрын
// Really useful, clean and optimized! // I love short tutorials like this!
@trashcaster
@trashcaster 2 жыл бұрын
A commented comment? Clever
@zendakk
@zendakk 2 жыл бұрын
-- Agreed, also applicable to e.g. Lua { and even good ol' Pascal, } # anywhere, really.
@Dreadnaut2560
@Dreadnaut2560 2 жыл бұрын
@@zendakk
@tjdewolff5104
@tjdewolff5104 Жыл бұрын
For the very same reasons you mention, like "readability" and " maintainability", I convert these multiple "return" functions into (apply drumroll here...) yes, NESTED(!) code! For some 4 decades now. In the process of conversion I discovered many an error like memory leaks. Applying multiple return-clauses in a function tend to obscure these clauses more often then not, eliminating readability. A return-clause should only be applied as the final clause in a function and the only when a value is to be returned. That value, by the way I explicitly demand to be contained in a variable, which is declared in the very first line of the function and is set to a recognised error value. This line is to be followed with a blank line and that sets the returnvariable apart. Literaly. What's more, nesting code brings you the benefitsof "just in time" declaration of variables. Think in terms of congruency of lifetime and scope. This you will NEVER fully achieve in this video. My 2 cents. Tjitte I work in 'C' only.
@Stratelier
@Stratelier 2 жыл бұрын
Talk about a helpful tip for programming in general! I remember some old projects in Visual Basic where I often needed to populate elements on a form with values pulled from an array, but doing so (necessarily) triggers the elements' defined "changed" event (which in this case updates said array with those values). As the versions of that language (VB2, 4, and 6) did not support programmatically adding/removing event handlers, my hack was: prior to populating the form elements, I set a global form variable (I called it "SkipEvents") to indicate there is an automated process running, and each "change" event routine likely to be triggered during that process would immediately check this variable first and if set, it would do nothing but return. (Not too different from using a *try...catch* block when you're running a routine that could reasonably experience errors.)
@jabvzla
@jabvzla 2 жыл бұрын
It is possible to add one more step, it adds all the conditions in an array and applies the "All" (or "every" in javascript) method. This even giving you the possibility to add conditions from other places.
@Konitama
@Konitama 2 жыл бұрын
Feel like this will only work if the method doesn't have other stuff going on in it as well... Otherwise all these returns are going to cause a lot more confusion when you're trying to do something else but it never executes the code because some other thing way up the list is causing the whole method to end prematurely.
@Schnorzel1337
@Schnorzel1337 2 жыл бұрын
Well if one function does more than one thing, you should replace it my multiple functions anyway.
@SelaMalka
@SelaMalka 2 жыл бұрын
Brilliant, please make more videos man, you're explaining so well!
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
Thanks! Have a few more videos in mind, but they might be a bit delayed
@ajtan2607
@ajtan2607 2 жыл бұрын
Or, if the language has operators && and || that does short-circuit evaluation, you can also do this: void DoSomething() { bool shouldAct = ( condition1 && condition2 && condition3 .... ); if (shouldAct) { // do something } } Since the expression is evaluated from left to right, it will immediately result to false upon encountering the first condition that is false, regardless of how many remaining conditions there are. It seems like everybody's got their own magical way of doing things. I guess the "best" implementation is the one that satisfies most (if not all) requirements for a certain project.
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
That's an excellent point, coding and best practises are still somewhat subjective. It's good to understand the reasoning behind these practises so we adopt them or reject them based on our own understanding and requirements. Thanks for leaving a comment!
@filodipicori
@filodipicori 2 жыл бұрын
I don't think it would work for this case, though, as some conditions have unique outcomes for a false return- the hint displays.
@CodingWithLewis
@CodingWithLewis 2 жыл бұрын
This is helpful in more than just Unity. Amazing video.
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
Glad it was helpful!
@tamaskarsai2072
@tamaskarsai2072 2 жыл бұрын
I learned about this about half a year or maybe a year ago. But the more people know about this the better.
@flootypie
@flootypie Жыл бұрын
It's interesting how things change. When I went through Uni (many many years ago) we were taught that a method should only ever have one exit point, and doing otherwise was absolutely forbidden. Glad to see more flexibility in use these days, although I can see how having multiple exit points could also cause problems...but I agree it's an improvement.
@JamesMakesGamesYT
@JamesMakesGamesYT Жыл бұрын
That’s a good point, there’s a lot of changes as new technologies and methodologies emerge. My understanding of the “only one exit point” rule is that if you have a big method it can be confusing if you’re returning “7” on the first line and “13” on the 30th line. If you try to keep your methods small then the guard clauses can really make your code a lot tidier.
@flootypie
@flootypie Жыл бұрын
@@JamesMakesGamesYT Yes, I've certainly come to agree. My favourite "new discovery" is writing self-evident code with as few comments as possible. The reduction of the old pressures of size and efficiency over everything else allow many convenient freedoms. Rediscovering coding after a 30 year break is very interesting.
@danser_theplayer01
@danser_theplayer01 Жыл бұрын
I do this a lot with a few simple guards like if ANY of these trigger then exit the function instead of doing what you want. But I don't know how you can use them with finer detail instead of basically making a giant OR guard.
@marcussacana
@marcussacana 2 жыл бұрын
Personally I like to put a enum with flags of the state, then check all object status in the same variable
@gordonzar992
@gordonzar992 2 жыл бұрын
That is typically called a state machine and is the preferred method of approaching this if you have a lot of states to handle.
@gordonzar992
@gordonzar992 2 жыл бұрын
You can up your game with something called "dispatch tables" if your language supports it
@LeorixSP
@LeorixSP 2 жыл бұрын
Prefer only one return statement for readability. You can && all conditions to attack in only one if and else if all other conditions separately for the hint text. One identation needed only.
@yidscq7990
@yidscq7990 2 жыл бұрын
Your voice is so cool and your content is actually useful.
@Kitsomo
@Kitsomo 2 жыл бұрын
I strongly believe you have the best tutorials i ve seen so far. This is a pattern people should use more in their codes . Cannot count the times i ve opened my old game jams and seen 10 if statements in a row.
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
Thanks for the kind words! Trying to create more of these types of videos in the future
@dicousdev2592
@dicousdev2592 2 жыл бұрын
This is early return pattern, its beautiful :)
@MohiDev
@MohiDev 2 жыл бұрын
Wow! In 2 mins I learned how to use if statements correct (Thats good that i don't have situations like that).
@FabiulousGames
@FabiulousGames 2 жыл бұрын
Great vid, I recently started using Guard Clauses and I can confirm that it has improved my workflow a ton
@gordonzar992
@gordonzar992 2 жыл бұрын
How long have you been developing games again?
@UngodlyDev
@UngodlyDev 2 жыл бұрын
I do try to keep my if statements separate but I've only used guard clauses without knowing they have a name and only a couple times. I'm about to refactor several scripts so this video will come in handy!
@vietanhnguyen1415
@vietanhnguyen1415 2 жыл бұрын
Short Video but make a huge impact on my knowledge. Sir, you are a lifesaver!!!
@Calculamatrise
@Calculamatrise 2 жыл бұрын
I've used this before, and I use it to this day. I've always had something against 'if' statements, and I don't know why. I do this all the time when possible.
@JustinBieshaar
@JustinBieshaar 2 жыл бұрын
Great video! We use the exact same method in games company I work for. We are actively reviewing on clean code approaches like this. Good you point this out! 👍
@sebimed5917
@sebimed5917 2 жыл бұрын
Okay, but what if my update method needs to check more than just the attack action, like jumping, rolling, etc. It can't just return if one of the 10 possible buttons isn't pressed so how would you handle that?
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
You could extract the guard clauses out to a method that returns a bool called "CanJump", "CanRoll" etc. Instead of a return in the guard clauses you would have a return false and then a return true at the bottom of the "CanJump" method like this: void Update() { if (IsJumpButtonPressed && CanJump()) { Jump(); } } private bool CanJump() { if (isJumping) { hintTextUi.SetText("You are already jumping"); return false; } if (!HasStamina()) { hintTextUi.SetText("You have no stamina"); return false; } return true; } Hope this cleared it up
@sebimed5917
@sebimed5917 2 жыл бұрын
@@JamesMakesGamesYT I see, that would actually be a good way to make my player controller script more readable. Thanks for the answer, much appreciated 👍
@jackoberto01
@jackoberto01 2 жыл бұрын
@@JamesMakesGamesYT Alternatively you could extract a method like void AttackLogic(), void JumpLogic(), etc with all the input actions and in there add the guard clauses I try to almost never put conditions in Unity Event functions like Start and Update because you know you might need to change them later
@RajveerSingh-yb6zq
@RajveerSingh-yb6zq 2 жыл бұрын
If (a) { print('Passed Gurad A"); return; } if (b) { print("Passed Gurad B") return; } if (c) { print("Passed Gurad C") return; } Print("Yay!! passed all guards") Consider the above code... One can easily assume the to print if the code in the "b" condition is very big then, While seeing the code in "c", it will seem like the only necessary condition to print "Passed Guard C" is that if c is true... That's why I feel that this is going to make it a little more ambiguous only... not fix it...
@fv4202x
@fv4202x 2 жыл бұрын
but there is return in the a. So its same I guess?
@tl1326
@tl1326 2 жыл бұрын
i know nothing of code but it looks to me as if someone were to use “and then” or commas but never use ‘period’ in an essay to break up text
@Rhidayah
@Rhidayah 2 жыл бұрын
This is back to my junior programmer
@TheThursty100
@TheThursty100 2 жыл бұрын
I've sent this video to a coworker, because he refused to use guard clauses. Most because "early return bad". He still refuses to use them and called you unqualified. Just thought you wanted to know
@Oshroth
@Oshroth 2 жыл бұрын
As a iOS developer I'm used to guard clauses as they are a language feature of Swift. E.g. Guard(some condition) else {do something; return} Rest of function body
@iamTakuu
@iamTakuu 2 жыл бұрын
I’ve always used my if statements like this when programming for school projects, but I didn’t know this principle had a name. Thanks!
@Frank_G_Finster
@Frank_G_Finster 2 жыл бұрын
Thank you for the tip! It really makes life easier as a newbie coder.
@cbhv4321
@cbhv4321 2 жыл бұрын
As someone who is very uneducated about this, wouldn't and statements in 1 if statement solve all your problems here and make this much more readable?
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
Great Question! In this case, no we can’t just combine the conditions using the || operator because of the hintTextUi.SetText calls requiring a different input string based on the condition. If we didn’t have the hint text part, yes you can use the || operator and have just one guard clause.
@sundarakrishnann8242
@sundarakrishnann8242 2 жыл бұрын
a very nice, short and informative video! You explained so well in such a small amount of time! Thanks
@tughloksiddiquee1714
@tughloksiddiquee1714 2 жыл бұрын
Love it, not just unity, it applies to programming in general. Would love it if you give more tips on c# and unity
@feha92
@feha92 2 жыл бұрын
Didn't you read the videos title? This only works in unity, and you can't even do it in regular c#, much less any other language with if-statements. Clearly.
@badwrong
@badwrong 2 жыл бұрын
Early returns are good and all, but this ignores the underlying issue of using to much procedural coding. Good design patterns and better use of abstraction and polymorphism is how you remove nested logic and needless condition checks. Yes, some cases just need an early return, but even the example in the video uses the mentality of "if something, do something". That is ok for beginners, but the better logic pattern is "when something, do this". This can be facilitated by what I already said, design patterns, abstraction, and polymorphism.
@theWebmasterify
@theWebmasterify 2 жыл бұрын
This gives me flashbacks to the YandereDev if else chains
@Mouamle
@Mouamle 2 жыл бұрын
I use this method even when writing huge enterprise level code, it's been proven to be the best.
@chefbennyj
@chefbennyj 2 жыл бұрын
I always use guard clauses. Excellent!
@netrogamedev3257
@netrogamedev3257 2 жыл бұрын
thanks james! this is gold for me as a self taught programmer!
@kody.wiremane
@kody.wiremane 2 жыл бұрын
I s'pose in a real game one won't be only handling a single trigger and a single action, so probably there'll be a sequence of if (isXTriggered()) { tryXAction(); }, and in those latters one will be having these guard clauses. Could've been mentioned.
@monawoka97
@monawoka97 2 жыл бұрын
Guard Clauses are all good and dandy in hobby projects but I warn against them in large projects or professional environments. It can be hard to spot early returns in methods longer then a single page and that can be a common source of bugs.
@DreadKyller
@DreadKyller 2 жыл бұрын
This is one reason why many large or professional projects require you to use code linting, which will yell at you if you exceed a specified npath or cyclomatic complexity.
@marcelocosta9620
@marcelocosta9620 2 жыл бұрын
Wow! This opened my mind now! Thanks for the tip.
@Ryöken17
@Ryöken17 2 ай бұрын
It's cool in a way, but there is a priority, can't you have an if and a print depending on wich one triggers ?
@knownas2017
@knownas2017 2 жыл бұрын
I want to learn Unity. Whenever I decide to do this, this will help me quite a bit. :)
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
Thanks, I'm glad the video helped! Now is a really good time to learn Unity, there's a lot of great resources online to learn for free. Unity have example games that you can download and add your own mechanics to, like a Mario kart clone and a FPS
@knownas2017
@knownas2017 2 жыл бұрын
@@JamesMakesGamesYT Thank You, sir. You're quite helpful; I genuinely appreciate it!
@dhrubasaha08
@dhrubasaha08 2 жыл бұрын
Hey, I'm newbie at this...but I have a question why do you use only if instead of else if and else after 1st if ?
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
Hey, the reason we only use an if instead of else if is because of the "return;" within each if statement. If the condition is true, we return from the statement so no further code is executed. Hope this cleared things up!
@dhrubasaha08
@dhrubasaha08 2 жыл бұрын
@@JamesMakesGamesYT thank you so much 💖
@bezcisla
@bezcisla 2 жыл бұрын
And what about methods/functions? For example what you wrote in video, you could create new validation methods for that.
@vinodakula3824
@vinodakula3824 2 жыл бұрын
Awesome video. So informative about writing beautiful and maintainable code. Thanks. Please keep these coming.
@waldolemmer
@waldolemmer 2 жыл бұрын
I almost didn't click because I thought the video would only be applicable to Unity. Please consider changing the title This video was enough to make me subscribe by the way :)
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
Thanks! A lot of this I learned as a software developer and now I’m trying to help teach good development practises to game developers
@MortalVildhjart
@MortalVildhjart Жыл бұрын
This has helped me quite a ton! Thank you so much!
@khatharrmalkavian3306
@khatharrmalkavian3306 2 жыл бұрын
Assembly programmers are used to that kind of usage, but I've seen a lot of higher level coders shit on it, saying that it's hard to read (which they always say about everything they didn't write) and that it's bad to have multiple return points in a function because you could miss some kind of required statement somewhere (which is stupid because it means they're not using RAII).
@jondycz
@jondycz 2 жыл бұрын
I love this! Sometimes i use guard clause and sometimes not, depends on how my brain approaches the problem. But code written in the guard clause style is definitely more readable and every time i have to re-read my messy code with nested if statements without any comments, i get confused as for how the code even manages to work xD
@bren.r
@bren.r 2 жыл бұрын
You shouldn’t nest things more than 2 levels deep, ever. Readability and refactoring above all else. It will save you down the road and keep your productivity level higher than if you neglected the constant refactoring and cleaning up as you go along.
@BinaryReader
@BinaryReader 2 жыл бұрын
Use this pattern all the time. Didn't know it had a name. I expect most programmers would arrive at this pattern on their own eventually.
@Skyfield12
@Skyfield12 2 жыл бұрын
Doing readable code has the same level of importance as doing executable code.
@josgibbons6777
@josgibbons6777 2 жыл бұрын
The title hides how language-agnostic this advice is, but I'll add some explicitly agnostic advice. Depending on the language, "f(); return" can likely be changed to return "f();". Again depending on the language, needing only one line may save you creating an indented block under the condition.
@accidentalengineering
@accidentalengineering 2 жыл бұрын
Also referred to as "early return".
@rohanphaff2640
@rohanphaff2640 2 жыл бұрын
Much love!!! I really needed this one to clean my code up :D
@alifarhadali5580
@alifarhadali5580 2 жыл бұрын
We need more videos like this
@demyanrudenko
@demyanrudenko 2 жыл бұрын
If there's any kind of statement after the input if, this won't work. Which is most of the times.
@Leitoz
@Leitoz 2 жыл бұрын
If you have 2 or more conditions that have similar actions, why not choose to use a logical "or" to further simplify the code? The code snippet would look something like this: if (isSprinting() || isBlocking() || isJumping() ) { hintTextUi.SetText("Cannot attack while performing another action") return } if (!HasStamina()){ hintTextUi.SetText("Low Stamina"); } Input.GetMouseButtonDown() ? Attack() : return ;
@Koktis
@Koktis 2 жыл бұрын
I wish they could learn me this in school... Bruh, thank you for that! PS. They are teaching us things that we never use in our life, so I'm running Unity instead of something like WIndows Forms which teacher doesn't know what he is doin in it... 🙄
@atajuan
@atajuan 2 жыл бұрын
I love these kind of stuff. Thanks for sharing.
@hugofontes5708
@hugofontes5708 2 жыл бұрын
Sometimes I felt like using a negated condition in a if was convoluted and avoid it. Not anymore, thank you
@mittensandsnowdrop
@mittensandsnowdrop 2 жыл бұрын
That's awesome. Such a neat demonstration. Made total sense. I'm going to go try it out right know! Cheers buddy.
@JamesMakesGamesYT
@JamesMakesGamesYT 2 жыл бұрын
Glad it helped!
Abstraction Can Make Your Code Worse
5:13
CodeAesthetic
Рет қаралды 650 М.
Is Computer Science still worth it?
20:08
NeetCodeIO
Рет қаралды 331 М.
АЗАРТНИК 4 |СЕЗОН 3 Серия
30:50
Inter Production
Рет қаралды 1 МЛН
OYUNCAK MİKROFON İLE TRAFİK LAMBASINI DEĞİŞTİRDİ 😱
00:17
Melih Taşçı
Рет қаралды 12 МЛН
Running With Bigger And Bigger Lunchlys
00:18
MrBeast
Рет қаралды 104 МЛН
Giving Personality to Procedural Animations using Math
15:30
t3ssel8r
Рет қаралды 2,5 МЛН
Why You Shouldn't Nest Your Code
8:30
CodeAesthetic
Рет қаралды 2,7 МЛН
Using Interfaces in Unity Effectively | Unity Clean Code
4:23
James Makes Games
Рет қаралды 59 М.
5 Signs of an Inexperienced Self-Taught Developer (and how to fix)
8:40
Naming Things in Code
7:25
CodeAesthetic
Рет қаралды 2,1 МЛН
How I Untangled My Spaghetti Code
11:48
Jim Makes Games
Рет қаралды 1,8 М.
Why I Don't Use Else When Programming
10:18
Web Dev Simplified
Рет қаралды 1,2 МЛН
Dear Game Developers, Stop Messing This Up!
22:19
Jonas Tyroller
Рет қаралды 715 М.
Cleaner Code: 3 Ways You Can Write Cleaner Code
7:41
Coding with Lewis
Рет қаралды 88 М.