Why I don't use the "else" keyword in my code anymore

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Thank god for this video. More people need to use guard clauses in their code. It's one of the easiest and biggest improvement someone can make to the readability of their code.

Reading code where guards are not used always cripples the mind.

👍︎︎ 30 👤︎︎ u/lIIllIIlllIIllIIl 📅︎︎ Mar 30 2021 🗫︎ replies

tl;dw?

👍︎︎ 15 👤︎︎ u/darchangel 📅︎︎ Mar 30 2021 🗫︎ replies

This a double edged word, just like everything else

👍︎︎ 14 👤︎︎ u/Willinton06 📅︎︎ Mar 31 2021 🗫︎ replies

And this is good example of Open-closed Principle in action :)

👍︎︎ 3 👤︎︎ u/blu3pl 📅︎︎ Mar 30 2021 🗫︎ replies

It's quite interesting reading this thread, a good few people are claiming that nested if else's are good but I think he really most people would consider it a code smell and that this way something funny lies.

Returning early is a good habit, if I have nothing else to do in this function why hang around and cause potential side effects. There was an argument against returning early back in C that has managed to linger but I don't believe modern languages need to worry.

The above being said, if a single method has lots of return statements then it may be a sign something is off about your design and you may need to add another layer because many returns probably means you are doing lots of Ifs which just causes the testing problems from above.

The approach the author takes in his video is sensible, push decisions down the tree, he has created a mechanism to handle each levels responsibility and made it extensible and there is one more level to go where you would shift recipes out to their own class and interface so a recipe book becomes a mechanism for finding a recipe but does not in itself know what goes into a recipe or how to prepare it. The problem is such a trivial example you do think it overkill but apply it to a real world problem and you will soon see benefits especially when it comes to fixing bugs or adding new functionality.

👍︎︎ 2 👤︎︎ u/Wiltix 📅︎︎ Mar 31 2021 🗫︎ replies

If this goes far enough, we're going to have a revolution of "elseness" in code ten years from now. People will discover the else keyword and start writing 10 point coding principles around why the else is the height of code readability because it flows more naturally inline with the business logic and natural way the business thinks about processes.

👍︎︎ 3 👤︎︎ u/Qubed 📅︎︎ Mar 31 2021 🗫︎ replies

Hm I am sorry but it is 20 minutes video about changing else to switch, I thought he will do some oo trick and remove if nd else

👍︎︎ 3 👤︎︎ u/VkeZiV 📅︎︎ Mar 30 2021 🗫︎ replies

Personally i prefer the nested but shorter code. Finding short essentially meaningless methods and classes just makes the project seem much larger than it actually is and much more intimidating. Having all the code in one class with a very few methods makes it easier to grasp from an outsiders perspective. Essentially in the end, as I fold all methods anyways so I only need to read the method names and their documentation.

Also it kind of creates an sloc inflation. Its just my personal opinion and when im not working on personal projects, i tend to follow the style of the other developers.

👍︎︎ 2 👤︎︎ u/TilionDC 📅︎︎ Mar 30 2021 🗫︎ replies

This looks great and everything but it is waaayyy too advance for me lol

👍︎︎ 1 👤︎︎ u/zokutexu 📅︎︎ Mar 30 2021 🗫︎ replies
Captions
hello everybody i'm nick and today i'm going to talk about why i don't use the else keyword whenever i'm programming now a bit of a disclaimer the main languages i use when i'm programming i mean this channel is c-sharp but on my own time i'm using java and kotlin as well and in kotlin you have to use it for certain operations and i will explain when i'm using it in c sharp as well but in general i don't actually use it and the reason why i'm making this video to begin with is because i brought it up in one of the comments and the people of the community wanted me uh to talk about it in detail and i'm gonna do that in this video by no means am i recommending that you should stop using it or that if you're using it you're doing something wrong this is just my perspective about why uh i think four years now i haven't really been using it and in fact if you get access to the sources for the videos i'm making in two years i've never used it outside of um any templates or any js libraries that i've used so yeah if you think that this is an interesting topic let's dive into the code and talk about why i'm not using the else keyword anymore now first i want to talk about something else before we look into any code around three years back uh a colleague of mine brought up something called object calisthenics and it is a a rule set of nine different rules written by a jeff bay as part of his uh the thought works anthology book now whenever i deal with these types of rules for clean code i'm very skeptic and i approach them very carefully because yeah there are nine rules there but doesn't mean i have to use them if i don't agree with them it turns out that many of them are applicable and with some of them i don't agree you can see them in your screen right now and if you actually want an object calisthenics dedicated video i can make one if you ask for it in the comments down below but the second one is don't use the else keyword and the first time i heard them like wait a second well first i'm not really using it that much but also why shouldn't i use it right why are you so blatant don't use it and i had this discussion with my colleague and we did a refactoring exercise and it turns out that it's not that you should remove it it's that you don't really have a need to use it in the first place um this is not really true when it comes down to razor or blazer when you're doing inline html and c sharp there you have to use it but if you're just doing regular code in your monolithic or micro service application there is really no need at least for the code i'm writing to use it and for that video i'm going to look at an example of course it's a simple example but i hope that it demonstrates in a smaller picture what the bigger reason is and hopefully we can see how we can make the code better by not using it and whether it's even worth at doing so so let me just close this and go to the program.cs and what i have here is just a simple application that creates a new instance of a bartender and it's accepting an input and an output mechanism in this scenario i'm using the console to accept input from the console and write to the console and then i'm constantly asking for a drink in a loop if i am to run this let me just show you how this looks like so the question is what do you want to drink beer or juice i will say juice and it goes here you go fresh and nice juice and then the question is ask me again what do you want i want beer so i'm gonna say beer and goes no not so fast cowboy how old are you and i can say 16 and then go sorry but you're not old enough to drink at least in the uk and if i do it again and say beer and i say 18 or more here you go your cold beer so this is the program that we're going to be looking at and the code we're going to be uh effectively refactoring so let's go in that bartender class and see what's what's here so what we have at the top is a function and action related to how we're dealing with input and output uh we're injecting that because i don't want to restrict this code to a single console you might want to use a logger you might want to use some other input mechanism and then i have a list of logical flow where you ask for the drink you say okay give me the input let me know what you want and then i say if it's beer do this if it's juice do this else sorry we don't do this drink oh yeah one of the things i didn't show is that if i put something that is not part of the recipe book then it will go to the last else state now right off the ghetto you can see that we have three uses of the else keyword first for the age input so if it's a valid integer for the age and it's then whether it's more than 18 and last to handle the edge case off we don't serve that drink now there are several things that are wrong with this with this method outside of the else keyword for example to me what rings a bell is that this class is violating a open closed principle from the solid principles because every time i want to add a new drink i have to go else if and say whether that equals a drink and add the logic here we can make this better but i won't start by doing that i will start by something else if we go back to the object calisthenics one of the other rules i tend to follow is the one only one level of intendation per method what does that mean well only only one level of indentation means that you start here when you start writing your code this is your level of indentation and you go all the way to here but you don't have any more nesting in your methods obviously that's not always achievable but in scenarios like this it is you could say something like you're going to grab this whole piece of code and you can say extract method i'm going to use extract method functionality and i'm going say server beer and or handle beer serving and i can move that code there then i can also say here serve juice and last but not least i will say extract method and available drink and in that way now you can see that the the method the initial method is way more readable and again readable is a very subjective thing and it's subjective to the eye of the beholder but the way i look at it it's way easier to see how the code flow goes and what my application is doing for example i'm getting the input the drink names here i check whether it's a beer and i'm calling the serve beer method and if i want to see what this serve beer method is doing i just go to it and i read it completely separate from the main flow and which to me is clearer now that being said here we're still violating this only one level of intimidation rule and we can fix that as well by simply splitting that part out so say handle invalid age or for beer we could say that and then i can also say handle uh beer age check and then i separated those i am now not violating that single rule of intendation and my extracted methods also don't violate that so by splitting those outside my code is now not violating the first rule which is you'll see how it's linked to the second rule um also you might be screaming in your head now that hey this if else should be switched to a switch and you're right i'll go ahead and i'm going to switch this if else if i'll statement to a switch and now we don't have the else keyword right i didn't explicitly remove the keyword here i just changed my if else files or else if um do a different type of check so i honored the second rule but i didn't really do it to honor the second rule i did because it makes more sense here to actually use a switch so what about the other ones right so um an envelope drink and serve juice they don't really do much but the serve beer actually does something you have the if the age is not possible then you handle invalid age else you handle a beer age check now is there any point in having this extra nesting with this else bit here because the way i see it i could return here because the code is not meant to go any further if in this specific method and i can just remove the redundant else and now i'm not using the else keyword i'm returning early not that returning early is the reason why i removed it but to remove the nesting and i don't have to follow that logic anymore just not there so by returning in the if statement if returning is appropriate after i'm splitting it it makes more sense to not actually have the else keyword there and my code looks a bit less bloated and that will do the same with the bare check obviously a writer will say you should change this into a ternary which is called ternary i think it's called ternary check but it doesn't look nice i generally in calls like this i would also extract this to something like a local function that is um is over the legal limit and maybe use that then that would also cause nesting in the method so i might extract it outside for now i'm just going to leave it as it is and what we're going to say is if it's more then return if not remove the else and that way we just eliminated any use of the else keyword in that piece of code this is a small like micro size of uh the use case but if you think about it usually outside of razer templates and blazer this these sort of things where you would use a dls keyword if you're doing something like very complicated algorithms um or if you're following a single exit point uh approach which i don't really recommend but if you're doing that then you have to use the else keyword but in code that i'm writing in kotlin java and c sharp i very much follow that approach because i just don't need to use it i don't have something against it it's just something that i don't have to use if you stayed until here you've seen everything i want to talk about on the else keyword but i think there is value in showing how you would refactor this code further because currently it's still violating the open close principle for example if you want to add a new drink to be supported you would have to create a new case and you would say i don't know some cocktail maybe cocktail that's very generic whatever the main idea is that you have to come to this method and edit this method so the edit is open for modification while it should be open for extension and closed for modification so for the rest of the video i'm going to address that if that's all you want to see until now thanks for watching don't forget to subscribe and i'll see you next time so how can we optimize this code now there's a few ways how you can you can do this but i'm gonna go with a very simple way that doesn't require me to use any other library like something like mediator some people say that you can fix the else keyword or not use it by using the state pattern and i agree but that's not really what i'm gonna do here i'm gonna go with a more um hands-off approach uh on the problem what i'm gonna do is i'm gonna make a new class and i'm gonna name this class a recipe book so every bar i'm assuming has some sort of recipe book where people know how to make those rings you don't really need to know how to make beer or juice but for the purpose of this video like imagine those are cocktails and i want all this to be automated so to just have a single ask for drink method and then automatically pick up any potential drinks that are available so what i'm gonna do in that bartender is i'm gonna say private read only recipe book recipe book equals new i could inject that as well from the constructor and i'm not going to do it but you could because now we're just binding the dependency on the recipe book so if you're using a database to get the recipes you really want to be injecting it so you can mock it and test it but i just want to keep this simple so what i'm going to do now is i'm going to go to the recipe book and i'm going to create a private uh let's say dictionary how about that yeah let's say dictionary and in that dictionary i'm gonna have a string which is a key and then the action would be just an action and i'm gonna name that recipes and i'm going to have a constructor and in that constructor i'm going to have recipes dot actually i'm going to initialize it and i'm going to have my recipes here for example i would have the beer recipe and then the way to make it this is a lambda i will populate this in a second and then the juice so same thing juice i think that i don't have to inject anything here most likely maybe i can actually inject to simplify this i can inject the the input and output so what i'm going to do is i'm going to inject those from the constructor initialize field from constructor for both of these and then i have the methods and now i'm going to take all of that outside of the recipe book of the bartender story and what i'm going to say instead is i'm going to use the serve juice method here and the serve beer method here and now every time i want to add a different way a different drink all i have to do is add the name of the drink and the method in this recipe book and then my bartender will know how to make it obviously i have to edit this code as well to make this work so i'm going to add a couple of methods in my recipe book but these methods are private and they're not leaking outside of my recipe book so what i'm going to say is public list actually i can make this an enumerable high innumerable of string and say get available drinks or drink names yep and i can say return recipes dot keys and now i can return the keys in a in a list or an enumerable and the reason why i'm doing this is because let me just initialize this recipe book in here instead equals new recipe book ah you know what i should really inject it yeah whatever let's inject it you go here and i'm going to inject you in a second and what i'm going to do because i don't want to edit this list every single time is i'm going to use string interpolation and i'm going to say recipe book dot get developed drinks and in order to automatically build this comma separated list of available drinks i'm going to say string dot join comma space and then the enumerable and now when i run this this will pick it up automatically from whatever is available and the other thing i want to do is i want to get the recipe from the recipe book so recipe book dot get recipe and i'm going to give it the drink name for me to get the recipe and ultimately what i want to do is i'm going to say i'm just going to invoke the recipe and this should just work so if i remove all of this code i'm going to now implement this get recipe method let me move it at the top so we pick that up and we put it here and actually that i'm thinking about it we don't even need this get recipe method because what we can do is we can have the bartender checking for whether the drink is available so if recipe book dot get available drinks dot does not contain the drink name then we just say output provider sorry i don't know how to make this one not exclamation mark and then we just return if they do know then we need to get the recipe back to do it so could i do it with recipe book dot um you know what i do need a good recipe i don't really need a good recipe i need the make drink method so make drink and i'm gonna say drink here and really that's it so i'm gonna create the method i'm gonna move it at the top i'm gonna move it here and this is the drink name and what i really want to do is i wanna get the drink from the recipe so drink name and i'm gonna just invoke that and now all i need to change here is that this bartender also needs the recipe book which also needs the same parameters and you go here here you go and now my code is there and if i run it again unless i really as you can see this is automatically dynamically picked up by the the dictionary we had and if i do beer not so fast cowboy how old are you 10 sorry but we're not making that because you're young juice here you go this is a juice something random sorry i don't know how to make this one so we have the exact same behavior but now if i want to add a drink and what drink should i add in fact this is not even needed this unavailable drink so i'm going to delete that and if i want to add an extra drink all i need to do is add the method for the drink so let's say i want to add a private void uh serve what's like old-fashioned which is in cocktail um here you go quite old school there it is and if i change this to uh old-fashioned i'm gonna just say serve old-fashioned and that's it now all i have to do is run the code i didn't modify any existing method i just added one and i added the thing in a dictionary if you want to go over the top with this you could actually just um use an um an attribute and put the name here on the method and then dynamically load it up with reflection startup or you could use something like mediator if you really want to go over the top or you could split those methods to separate drink handlers but my main point going back to the original point which is why i'm not using the else keyword is because i really don't need to i'm following a few rules that are more like rules in my mind than i'm thinking and doing them that make me not have to use it now i understand that this might not be applicable everywhere but if you compare the code where we started and the code where we are now i think it's way more clean way clearer again very subjective but it works for me so it might work for some of you that's all i had for you for this video thank you very much for watching special thanks to my patreons for making these videos possible if you want to support me as well you're going to find it in the description down below leave a like if you like this video subscribe for more content like this and ring the bell as well and i'll see you in the next video keep coding
Info
Channel: Nick Chapsas
Views: 157,484
Rating: 4.5352082 out of 5
Keywords: Elfocrash, elfo, coding, .netcore, dot net, core, C#, how to code, tutorial, development, software engineering, microsoft, microsoft mvp, .net core, nick chapsas, chapsas, Why I don't use the else keyword anymore, the else keyword, don't use the else keyword, else, don't use else, code, kotlin, java, python, javascript, best practices, dotnet, .net
Id: _ougvb8mT7k
Channel Id: undefined
Length: 20min 40sec (1240 seconds)
Published: Thu Feb 11 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.