How to write clean code
Skills:
API Design60%
Key Takeaways
Teaches clean code principles and best practices for writing professional-level code
Full Transcript
welcome welcome welcome i cannot be any more ecstatic than to build a course on clean code maybe testing i'd like me some testing but clean code is really a passion of mine it's something that's going to really level your career up and level your skill set up in a relatively short amount of time once you understand some of the concepts behind it so on these courses i like to use the sort of gathering title or the grouping title code like a pro because that's really what i'm trying to get you to do i'm trying to get you to go from aspiring engineer to a professional engineer what that actually means and here i will be your host uh teacher whatever you want to call it sensei mentor general uh hence i'm using my little funny portrait here i had painted of me royalports.com if you want to have some fun to really show that i know what i'm talking about here but uh my name is dylan israel i'm a senior software engineer i currently work at amazon and uh we're gonna be doing some cool stuff man so what are we talking about here oh we're gonna be talking about variables functions classes comments not anything that's super intense not anything that's super out of the norm you know i'm not going to hit you with recursion i'm not going to hit you with triple node binary trees or graphs or no we're talking about how we can fundamentally write cleaner code to make our life easier what does that mean what are our objectives well we're going to write code that's going to be more searchable readable and understandable that's it very simple and by that you're going to be able to write professional level code you see what i did there kind of fun right so who's this course for well it's for aspiring software engineers you're just learning a code today if you just stick in here a little bit you'll come out a better developer in this short course you'll learn quite a bit it's definitely for junior engineers that's when i spent my time looking into the clean code that my tech lead recommend senior engineers it surprises me quite a bit how many senior level software engineers are senior just in years of experience and not an actual skill it's very common at least in our field in my experience for people to have 10 years experience but they repeated that first year 10 times i don't want you to do that and it's going to be for people who are interested in quality assurance qa writes code 2 in their own way and this can help them quite a bit and then of course those just looking to better understand javascript because that's what we're going to do and you're going to pick up a few of the things in language that we can do to make our code more readable searchable and understandable so why do we do this at the end of the day well ninety percent of your job is reading code believe it or not even if it's greenfield development you're reading code you're writing code obviously but you need to be able to understand what it is that you did two months from now three months from now and it becomes very hard very quickly there's an old joke when it comes to coding that when i wrote this only i and god understood what it did and how it worked three months later now only god understands and we're trying to eliminate that issue it's a natural progression of your skill set we want you to become better engineers you want to become you should hope to in whatever profession that you are part of to become more skilled at it employers value this skill i can tell you that for me there's three things that allowed me to double my income early on in my career testing and clean code in the solid principles so it's a skill that employers value is you're going from smaller to mid to large size companies people are going to really value you being able to write clean code and from a very practical standpoint the payoff of the effort to learn to implement clean code which makes your life easier and is valued as a skill you get 10 times easier the payoff for the amount of effort it takes to learn because it's some very fundamental stuff so i'm very excited about this course i'm not just saying that because they're paying me i really am i this is something i'm very passionate about if you've ever watched my youtube channel or anything like that i'm over here harping on this and i've harped on it at every organization i've ever worked at but clean code is a must-have skill and something that's going to really make you a better software engineer so with all that being said hyping it up let's go ahead and jump into it and see what we're talking about here germa takes a very challenged approach to their courses and for the most part that works for a lot of things it's going to be a little harder here with linters so we're going to do a little bit more slides but we have a nice challenge at the end should you choose to accept it and i hope you do so what is a linter what it basically does is it's some conventions in your code to make sure that you're standardizing it and make your code more readable a lot of times and better it could be simple things like missing white space where you can see that yellow squiggly there and you hover over go and tell you what you need to do to fix it right what the issues are it could be other things like disallowing console logs and even breaking it out between oh yeah you're allowed a console log and a console table but maybe not console info it's very powerful can do quite a few things it can even enforce standards in your code such as public variables go after private or vice versa and so on and so forth no empty constructors in your classes a lot of things and they're usually very customizable and on top of that there's a lot of already pre-defined ones that you can just import you don't have to go and figure this all out on yourself i like to go in sometimes and tweak it to make it more strict i think strict is good now one thing i would tell you to make your life a little bit easier depending on which ide you're going to use there's usually going to be a setting you can turn on that it auto links for you as you go if it can't it may not always be able to because the actual linting may in fact be more of a warning hey this might change your logic but if it doesn't change the logic you can go ahead and envious code at least have it format on save as well as have it fix the lending errors it can unsafe and just let it automate that process make your life a little bit easier now i do have a bonus challenge here for you i'm not gonna go on this journey with you but i'm gonna go on the rest of it with you so don't worry about that but what i'd like you to do is go ahead and add eslint to one of your github projects that you have out there something where you're like hey i don't have a linter on here i want to see maybe what it will tell me how i can improve i've included the link here to the getting started guide on eslint.org and just keep in mind depending on the ide or text that you're using you may have to add an extension but the guide should walk you through all that good luck i hope you do it and i hope you do it in all your future projects let's go ahead and move on with the course all right welcome to the clean code or as i like to call it it's spicier title code like a pro the variables introduction i am dylan israel as you already know and what we're going to be doing is we're going to be talking about how we can write cleaner code specifically with variables we're going to have three main objectives when we do this we want to have more searchable readable and understandable code a lot of bulls there but by the end of it you'll be able to write cleaner code this is important how are we going to do that right those those these are just words right we have three main objectives but how do we accomplish them well we're going to accomplish them by following some language standards making sure that we're doing what the average in this case javascript developer would do now a lot of these items you're going to be able to transfer between languages that's what's so great about standards and clean code and you know practices and design principles things like that is it's language agnostic although of course we're going to be doing in javascript we're going to show the benefit of limited scope we're also going to talk about creating new variables versus reusing when and why to do that the importance of eliminating magic numbers how choosing a name to describe what it does but not how it does it is very important we're also going to do what i call the parent or significant other test and all i mean by that is if a variable name doesn't make sense to my mother who's not very tech savvy lover of death but that's the truth then it's not a descriptive enough variable name and we can do better we're also going to talk about when to use long names and short names and a lot more so this is probably the part of the course which is why we're starting with it that can have the most impact immediately so let's go ahead and jump into it so let's start with a basic example of just adhering to some of the language standards that you would expect in javascript typically when you have a variable like count here if it's in all uppercase we're expecting this to be a constant typically it's just going to be an imported constant at that but here it's not following camel case now some of your linters may catch this but it's important to know what your standards are in your language of choice and to follow them the reason is it's more readable pretty straightforward now as we're looking at this we don't actually ever go and reassign the value again your linter may catch this but this would typically be a const but is it even actually fully correct do we actually even do anything with it no not really we can probably just eliminate this and change some of our logic and then by doing that maybe we can actually go and see if there's a better name that we can go and update items with now let's see instead of count being equal to zero here and again this this method it's not really important what the method does we're trying to adhere to standards right who who really cares what it does so is i less than them and we've eliminated that but then you see here on line seven with our variables that we're sort of modifying our original input usually not the best standard so what would be actually a good name here well what about total multiplications and we simply start it by initializing it equal to the number that's what we're doing here we're trying to get in fact the factorial total and we go ahead and change this number to total multiplications but don't always settle on your first name think about it for a second your variable names are going to be something that is going to be the most descriptive item in your application it's oftentimes going to replace comments which you'll see later on in this course so maybe factorial total would be the best name and now by having our factorial total we know exactly what the objective here for factorial total is and we have created something that follows the javascript standard but really the variable naming convention standard something that's a little bit more descriptive so let's move on to descriptivenames.js and i want to give you an example a very basic one of the significant other tests as i call it now before my girlfriend left me i would have had her chime in on this and would have been very funny so i will do my best acting hey baby what do you think a variable d stands for don't be gross dylan i was like right well what do you think a variable today's date stands for well clearly it stands for today's date now in this case it's kind of silly right because it's such a small function but you get the idea we've now eliminated something that may be lost in context now we'll talk more about short distance variable naming and long distance variable naming later on but let's look at a more realistic example now all right so we're at our first challenge here for our variables for clean code now a couple things to note you can see down below we have a function called get user's full name and that takes in an array of strings with a first name followed by middle name and last name and what we want to return from this function is the first name the middle initial and then the last name that's what this does how might we go and make this more readable now that's all i'm going to say i want you to see if you can figure out a couple things on your own and how to make it more readable but if you need some direction there's a hints.md file here i'm not going to click it because i wanted you to make that distinction yourself that might give you some direction but think about it what we've done and there's going to be some ways that we can make it more readable that we're not going to expressly talk about and i want to see if you can come up with it but if not don't worry we're going to do it in just a second were you able to do it if not no worries let's talk about some of the items that we can use here some of our best tools are simply to do things like array array deconstruction now you may have started by going and creating a first name is equal to user names zero and let's go ahead and actually do that and then maybe we did a middle initial equal to this right here then we did our last name this would have been great and it is great i should say because you would have practiced something that we talked about of opening our descriptive variables and then we paste them in here obviously this is definitely a much better solution than was there before we have exactly we know exactly what this is based off of the array values instead just sort of throwing it in there we can now see like oh cool this is actually the first name and the middle initial and the last thing being passed along it's kind of hard to follow some of it though with this spacing so we use some of the es6 string interpolations with backticks here to actually paste it together so it looks a little bit more readable we know exactly what's going on and we don't have to jump these plus signs together and do all that craziness that you really had to do in the past and get rid of that we made it just a little bit more readable using string polation and then some descriptive variable names now at this point this would be fine but my personal preference would actually to be use some array deconstruction and here we can do it like so we're on the let's get rid of this zero let's take that first value out of user names called first name and then we'll have a middle name here and then we'll have a last name because that's the order that's going zero index one index two index and then we can just go and create our middle initial from our middle name set it equal to middle name the first character with that we have a couple more lines of code that's fine what we're really going for here is readability and this is much more readable than what we started with still get my full name down below i'm going to call this challenge 1.5 because it's not really something we expressly went over but we kind of did talking about variables but how might we look at our very basic cat class here and say to ourselves does any of this look redundant and see what we might change go ahead and give it a shot now there's not a lot of code here so maybe it's very fairly obvious but one common thing you'll see again and again let's go say we have my little cat tito right and we'll say keto is equal to our new cat class again and again i'll see properties that have this prefix of the cat name and it's a it's definitely a bad pattern to start it's redundant so in our case tito dot cat age so he's 12. and then we have keto dot cat name and we'll say pito has now decided to upgrade to a milo this is essentially saying cat.cat right we don't need that so a better way of changing this is to drop that prefix oops there we go and same thing here age and now it makes a little bit more sense for the tito dot age and keto.name which is really cat.h and cat.name so think of that when you are using your class properties your objects you're following the interface segregation principle which is part of the solid principle it's not something we're going to get into this course about but i like mentioning these sort of mid-tier higher tier things so that eventually on your coding journey you've at least heard of it and maybe you'll say i remember that one crazy guy mentioned this thing maybe i should look into it that's what i'm going for here magic numbers are something that will perplex you if you've ever had to work in a legacy application or even your own code a couple months back there's an old saying in programming that goes when i wrote this code only me and god knows what it did a month later now only god knows so that's that's an old thing uh so we want to make it more readable and eliminate some of these magic numbers not really important what the code does is calculating an orbital period with an array of values but what is this number do you know what 6367 447 is or do you know what this 398 4418 is i honestly don't i had to go back and rewatch a video where i did this but you know what i could do to make this so much easier so i could go and create this variable called earth radius and set it equal this now i'm eliminating magic number one that makes more sense where i'm going and getting the earth radius and what i also could do to figure out what this is here is i could go and i could store that in a variable called the gravity metric and store that like so and bam now when we go and we have our gravity metric we know exactly what those numbers represent there are no more of these magic numbers that are there here or there and all this other stuff and we could even clear up a b and c to see what that is make it a little bit more um a little bit more descriptive but that's not what this is about this is about these magic numbers that we can then go and provide context for what earth radius is what gravity metric is and we'll actually circle back to a similar example of this of some items that we can do to improve this further but for now we'll stop right here you know i wanted to kind of make a point here about how hard it is sometimes to go back and retroactively do these things you know i wrapped this up and the editor was like hey why don't you go and fill in a b and c here just so that we complete and it makes a lot of sense right and i really struggled because they weren't descriptive variable names do i know what a is i can probably figure this out but really the intent here is have two pi so okay cool we figured this one out as i go in here and replace a there do i really remember when i solved this what c is representative of this equation the math pal plus the object's average alteration no not really to be honest i mean we can make something up here just to give an example so let's say this is like the grava we're making stuff up for sure gravity circumference gravity circ reference sorry i don't i'm a bad speller and we'll put that as r c then b i can really tell you but maybe we'll just say the um total gravimetric right you can definitely see how something in this where it's hard to go back and put yourself right back in that context without a lot of additional work and really start understanding especially something so math heavy but keep that in mind as you're going through here that you know when you're working in the code that is the time to think about it because you're in it and it's all clicking and you know you know exactly what you're doing and when you're doing it so with that being said guys let's go on to the next screencast all right we're at our second variables challenge here and this one's specifically testing magic numbers now it's kind of a two-part challenge one i want you to come up with a better name to want you to figure out if you can kind of see what time 86 million 400 000 is representing and if you can't that's okay because this is the exact point of why magic numbers can be caused a lot of issues go ahead pause the screencast see if you can do it were you able to i wouldn't have been able to just for the record but what this actually is is milliseconds in a day so one thing i wanted to show you is not only you know go ahead and rename this to something that makes sense but also when dealing with items where they're calculation based instead of putting this number and i'll go ahead and just put it right above here a better use case for that is actually just show the multiplication or show the calculation to show how you got there so how do we get there well there's 60 minutes in a day 60 seconds in a minute 24 hours in a day and then a thousand millisecond seconds i think it says that backwards so um 60 seconds in a minute 60 minutes in an hour 24 hours in day 1000 milliseconds and so we get our full multiple there not only do we get a context of the variable we also see how we get to this calculation here which is a lot more descriptive than simply throwing the 86 million in there you know proper spacing and return statements will make your code a lot easier to read as you go and start working with this stuff so there's actually a great eslint rule here that i've attached called padding dash line between statements and it used to be called used to have a similar one there's like return statements specifically for returns but this is more general and specific and that one's been deprecated but making sure that you have proper spacing is really crucial to making your code more readable so obviously in terms of line breaks you know if there's a comment here between a function that's not related you won't have a line break right if you have an instantiation here of our our variable you want to break it up from your logic statements and by that very statement you also want to have your returns have a new line before your returns typically my personal preference is never to have a return statement or if statement rather that's on a different line you can see how already this is cleared up quite a bit and it's much more readable same thing goes on with breaking this up in our switch cases we can have our case with a new break each and every time like so and now with proper spacing and returns we have something that's a little bit more readable as we go through it's not all jumbled right when we think of writing an essay what do we do well sentences are all sort of similar but when we get to a new paragraph it we start breaking it out we have punctuation right it's not just one giant long run-on sentence and the same goes for your code remember good code should read cleanly and easily and shouldn't be a task and with proper spacing and return statements with line before return statements that's what we're going to have all right welcome to the code like a pro or the clean code functions introduction a lot of cool stuff as always we have our owls whatever almost when we're writing clean code well we want to make it readable searchable and understandable when it comes to functions so how are we going to do that well by writing small functions functions that really have a single purpose making sure that we don't have these massive functions where they're doing a bunch of things we're gonna start also eliminating these boolean flags a lot of people throw in where a function does two things one if it's true one if it's false that we can read the function from top to bottom and it all makes sense that we correctly name our functions we also limit the parameters we keep things dry we avoid side effects when possible and we make sure not to have globals so quite a few things here let's go ahead and take a look at some examples and practice a bit all right so let's start talking about limiting parameters in your functions you can see here in our you know clinical bad example where we are getting a user's full name all it's really do is take the first middle last and even the nickname and concatenating it together once you get past about two parameters you need to start thinking about is my function too large and is it really doing a single thing and if it's not how might we go about solving that well in our case here it is all related right this is all our naming information but four parameters is a lot it gets hard to start juggling these things so a good implementation of this is to simply actually you can sort it i won't call it cheating but it's much easier to have maybe a username that takes in our object that we then can go and do username.first username.middle dot last and then user name dot nickname this allows us to pass in a single parameter only really juggle the one and uh we'll put a two on there there we go so it doesn't get upset with us but it allows us to juggle a single parameter to find an interface so we then can pass to and from instead of these strings that who knows what we're going to be using again and again and makes it a little bit cleaner as we move forward all right so if you remember the variable section we talked a lot about naming variables a lot of same items apply to function names but we're going to cover two main cases of how they differ to make sure that we're doing the naming of functions correctly so let's talk about that now one of the things you'll see time and time again when naming our functions is the incorrect nature of not using a descriptive enough name so take a look at this add user and just assume that in the background you know we get our data we do whatever we do with it and then we add it to the database down below here are we really adding a user are we adding a specific type of user well in our case a more descriptive name to really say what this function's doing is this is adding an admin user we want to make sure that we make that clear so you want to describe your functions for what they actually are doing not just on a low level or a high level but on a low level another common thing when naming your functions is not having a standardization for some of the naming conventions to go with it now every team is going to be different on how they name things but the standardized stuff is very crucial so let's take a look at two ways here we're retrieving an admin by id and down below we're getting a user by id these are you know two different methods one specifically for an admin one's for a user but the fact that when we retrieve something that we aren't standardizing it to be get admin by id when it's get you do the same thing when you're doing a a crate crate admin delete admin create user delete user when you start creating the standardization it makes your code much more readable and as you go and you start doing code reviews and pr's and things like that as you go into more advanced dev flows and dev practices as and workflows as you work some of these items you'll start to catch in prs it'll make your life a little bit easier so keep that in mind with your descriptive names and your standardization of naming for what a method or a function actually does all right welcome to the function naming and standardization challenge a lot going on there in terms of the challenge name but what i want you to do is take a look at these four function names and see if there's maybe some better naming that we can get behind is there anything that we can standardize is there something that's maybe a better name all right take a look that's all i'm going to give you see what you see and uh do your best all right we're able to do it some of our answers here obviously may differ you know clean code is one of those things where it's more about trying to get to the destination than just ignoring the destination and so what i mean by that is some of our stuff might be a little different that's okay so let's take a look at add message here right fundamentals we want to do our camel case we also could probably do a more descriptive name here where this isn't really adding a message similar to our type here we have an email so like maybe even variable renaming email data or just email and it can still take in a message and maybe we'll even rename this right add email perfect you depending on how your application runs you may have ad this could also be created typically in my application when i go and do a post to the database or i go and i create something new i'm going to use this as my prefix same thing with this empty admin anytime i get something i return i follow the convention here of git and we can do empty admin not maybe the best descriptive name but you get you get the idea instead of empty admin perhaps like new admin right and then we have our two deletes here and they have different functions in the sense of what one deletes a user one deletes an admin or one removes a user one removes an admin so let's just maybe standardize this prefix a little bit here and do delete or vice versa change it to remove really it's about taking a look and thinking about is our function name doing what it says it's doing and are we following a standard convention so that as i go through the code base it's a little easier to figure out what it's supposed to be doing let's talk about a little bit about encapsulating conditionals remember back to our variable section really what we're trying to communicate there is the power of good naming conventions and we're trying to do something very similar here and you probably remember that a lot of times we store them in variables obviously here it's more about storing pieces of logic into functions very small ones that we're going to create and in typescript it's actually really nice this isn't a typescript video but we can start having these private methods so that we really can go and showcase that hey this is never actually supposed to be a public function or at least used that way but here in our encapsulating conditionals what we're really looking at is hey this can get very ugly very quickly my rule of thumb is pretty much anything larger than one conditional and or one one check in our conditional i start to throw into some of these smaller methods and if it's greater than two i definitely do it one hundred 100 of the time now this is pretty small but it's all about the demo purposes so how about we actually make this a little bit more descriptive well one potential way is to go ahead and do the variables that we have talked about another is actually to go and create a function now you're going to have to make that distinction based on how much logic there is how many checks there are this is kind of small so either one would work but really you know use your best judgment now what are we checking here well we're checking if a user is active and a user is the primary account holder and so if that's true what are we trying looking for well well we'll say create a method say get is user primary active account something like that and it's going to take in a value of user and really we're expecting a boolean and instead we'll go ahead and copy this over put this in our return statement because the the intent here you can see the name is here is even rather long right so it's not a short name it's not a small name and of course fastener user now we have a descriptive function in our conditionals and as this primary active account changes perhaps we have a date check we're now housing this in one location and we can sort of break it out you know you would even maybe consider doing something like this where even within here we start using some of the variable stuff you know is primary account which is probably not what you're going to do in a nested if with two checks but here we can sort of take it one step further even start combining some of these items and another you know const is active and if we go ahead and set that equal to this part a little nice little line break here for readability it's actually one fantastic lint setting that you can do for return statements always have a line in front of them i highly recommend you turn it on here we go we have a little method that's going to go and be used to describe a different item and you can you can kind of see how we can continue to expand upon this but sort of abstracting it and encapsulating these conditional statements so really any of them greater than two i'd highly recommend that you do this okay so let's just review real quick what we did here we created a function a descriptive function to break down a piece of our logic in our nested conditionals conditionals being the if statement we even use some of the variable naming that we discussed earlier on in the course to kind of make it even more descriptive now as es2020 comes out you're going to see this more and more as they've added private properties and private methods and you're going to see more descriptive functions and using in the conditionals because then you'll of their private access scope um don't want to dive too much into that but really just try to understand that the main intent here is to get the non-primary user it's not to have a whole bunch of logic that has to do with the primary active account we can break that out into its own private or personal function like this and house it and give it a simply a descriptive name that's really what we're trying to do here all right encapsulating conditionals this is our challenge for that you can see here we just have this sort of get loading state that passes along some string based on what's happening it's not really important what we're looking at here is that we have maybe some if statements that are a little complex right they have three different inputs and you may perhaps look at this and say hey i could swap in a variable or depending on the complexity you might swap in a function to encapsulate it either one would do we're going to practice a little bit here by encapsulating our conditionals and functions go ahead and practice writing some functions here that are going to be descriptive enough to encapsulate the logic that's in those if brackets were able to do it let's go ahead and give it a shot so this is saying hey if a user exists with a double bang right and it is in fact loading and doesn't have an error go ahead and return finish loading so how might we write that well we have a function and it could say has user loaded maybe successfully that sounds good here we'll just take the state object and then we simply can return what's here this over in a more real world scenario you might have something more complicated than this but i'd probably store this in a variable but we can do it here with our function so has user loaded successfully go ahead put that in there very descriptive pass the state cool now maybe this one you know we'll say user is still loading function is user loading we'll pass the state here and we'll go ahead and copy and you know what this should also be successfully because that leaves out this last part we'll return here's user loading successfully do that function sound method because it's not in the class it has to stay in here now you can see we kind of have two methods one say that it has loaded and one that it is loading and it makes it a little bit more descriptive as well as encapsulate some of this logic because really what we want to do is get the loading state in these sort of sub sections we've broken out all right this is one of my favorite sections when it comes to writing code like a pro and writing clean code because it's also one of the most misunderstood sections that's comments and that may seem like a strange thing to you because a lot of you when you first start learning to code you're going to be at this comment that computer science programs are teaching you know aspiring developers a common everything and part of that is simply to go and teach you to actually understand your code but it doesn't stop there unfortunately as you go from aspiring software engineer to junior software engineer which is where it needs to die and so a lot of this section is going to be talking about how to write good comments and how to eliminate 90 of your comments which if we followed the previous sections we already talked about good variable names and good function names and if we did that most our comments aren't needed because what that is oftentimes in the bad comment category is a showcase of your code isn't readable enough thus i have to comment it not always the case but most of the time nine times out of ten so we're gonna be talking about what are some bad comments and what are some good comments so what are some things that makes comments bad right well as i explained oftentimes they're unneeded and they're used to explain bad code right another issue is that you have to maintain these things their additional level of maintenance and sometimes it's just leftover code that people are afraid to change right sometimes people put comments about things that version control takes care of and and markers in the code which if you're having to mark your code oftentimes you need to understand that maybe it's a different file maybe it's different intent and their markers shouldn't be there it's very very understood that if i'm having to put something in a file to say hey this is different than the rest of the file then it's a different aspect unless we should take it out and to do's um i've worked on projects where things change on a daily basis you can't ever trust to do so those are some of the items that make comments bad what makes a good comment short and concise these long comments that are very detailed oftentimes sometimes they should be good they're good but usually it's a sign that your code is over engineered or there's issues provides value this is really crucial and we'll showcase a lot of examples that i think some people are going to relate to when they started early on in their career to see something that doesn't provide any value and with good variable names and good function names we can eliminate a lot of comments sometimes we have business logic that wouldn't make any sense to anybody and that oftentimes clarifies why some code is needed when it involves business logic not how the code runs but logic as far as the domain specific is needed um and often times a warning for something that is of utmost importance there's a line in a project i wrote for a billion dollar company that if you remove this certain module that looks sort of strange out of place the whole app will fall apart because because of the intermingling of a angular web app with a asp.net application that was necessary at the time and then legal comments things that you absolutely have to put in there so let's go ahead and look at some examples i know that's a lot of talking but this is a very important section and there's and it came after the variables and the functions and all the other stuff because if you can do that we can eliminate a lot of these comments and clean up our code bases quite a bit what we're looking at here is a function to return all of the longest strings from an array that has strings in it so if there's the longest one is 10 characters we're going to turn all the 10 character words that's in that string array i actually wrote this when i was learning to code about six seven years ago which really makes me feel kind of old and how time flies but that's a separate story now what we're gonna do right now is utilize some of the variable names and the function names to eliminate some of these comments and have a more readable code base so it's going to be some good practice supposed to eliminate some comments that really we don't need now let's talk about start from the top and work our way down if you have to leave a comment for what a function does oftentimes you have a very poor name or the function is too large in this case this is a fairly small function so i think our name is actually incorrect and longest string sounds singular we're not returning the longest string we're returning longest strings and because it's a git and we want to standardize our calls maybe a better name here would be get longest strings we know it's returning something we know it's returning the longest of something and we know it's returning plural here hence the plural now here initialize the long string to the first value we don't really need this initialize but this variable name here let length length could be anything length is a very generic name would be a better name maybe longest word length because that's what we're going to use it for down below we're gonna have this placeholder variable that we're gonna go and set for anywhere that gets updated so let's go ahead and make those changes real quick now that we have that we have this other comment checks if current string is longer than the current longest is this an overly convoluted if statement to me this looks like a very singular purpose it's very straightforward is the longest word length less than the current word length i don't think this needs a comment this is a perfect example of something that doesn't need a comment right this reads very clearly we set the longest word length we compare the longest word length in a for loop this shouldn't be something that needs to be commented i understand if it's your first programming class but down the road not so much now same thing here is this filtering yeah filter take our array filter it's the word that length equals the longest word length we don't really need that now where we can make an improvement is strs that's sort of generic what about longest words so what we've done here is we've eliminated comments that we now have to maintain there that we had to maintain we eliminate some comments that really didn't really have any other purpose to describe this if statements very straightforward very simple and we updated our variable names and our functions names to be more readable and now we have less code we have to maintain in my opinion it's more readable and we've simply applied the function and variable naming to our better comments which in this case is actually removing a lot of comments let's go ahead and look at some other examples let's talk about two more really bad comments that i see from time to time the first one not so much as version control has gone much better with git but version control and log comments things like this where you know you have dates and uh you know a comment and then you know who it's by who did what on when this is what version controls for we don't need to muddy our code base with comments like this so if you see something like this delete it delete it delete it delete it so i'm going to leave this here just so you can see an example here and then a quick note to removing commented out code i die a little bit on the inside every time i see a piece of code in my app they just comment it out version control keeps track of these things and oftentimes what code is doing that is commented out really the only code you want to comment out is one you're actively testing and playing around with right this makes a user go and think why is this commented out should i leave it probably because most developers are very scared to think to leave this in there might i encourage you and my stencil is delete it just remove commented code we don't need commented code in our code base version control again we'll keep track of that and it just adds confusion it's another thing that doesn't need to be maintained what is this and things start getting out of sync so you always want to make sure to remove that commented code and not to leave these silly locked messages either okay visual markers so why are visual markers oftentimes a bad practice well usually what they're doing is they're either providing information that is very apparent and there's no need to provide that information or it's trying to make sense of something that probably should be in a different file right and so oftentimes you'll see i'm in one of two ways you'll see on what the the dots have something like this where like you know by convention for instance your dependencies usually go at the top of the file and you know most of our linters and things like that will take care of that so there's really no reason to even have a comment like that and then you have super unnecessary ones where take a example of our class here where you just go properties right properties almost always go first and our linters will even ensure that and it's very apparent that that's not really necessary now in a case where you have multiple files like this you might even see user class admin class things like this to show a distinction between the two this is a good example of where instead of actually having a comment and getting rid of it go and create a new file right go and do your admin.class.js or something like that and instead take this gut it out in one file put in another file of course get rid of the the comment and get rid of this one as well because really at the end of the day you know there's a little bit of disagreement on this depending on who you ask but in my opinion you want to have a single file per class and that'll make your life a little bit easier and also eliminate some of these visual cues that really at the end of the day are good indicators of a anti-pattern to showcase that hey maybe our file here has multiple purposes and that is an issue in itself so when you see those visual cues think about it see how you might be able to break it up to make it so that you don't need it and make your life a little bit easier one last thing i wanted to add on here it didn't really need a entire screencast for it is don't leave to do's in in your code you know you might have even before put to do move into two files right something like that at the end of the day priorities change you things change and just be like nike and do it no more to do so keep that in mind all right we're on the visual markers challenge and what i'd like you to do is simply clean up some of these visual marking sort of comments to the best of your ability i can really tell you how or what to do in terms of the instructions it should be pretty clear it's a very similar example to what we demonstrated earlier so go ahead pause the screencast and see if you can solve it were you able to if not not a huge deal a lot of this is simply removing things that we don't need like the dependency visual marker or a marker that says properties right our properties in our classes are should by convention go to the top of the class also to do oh no to do's as far as these pet class and dog class markers go and create a new file we'll go ahead and create a new file we'll call it dog dot class dot js and then go ahead and move this over to our dog class command v and then jump back down to to our here and we can eliminate these comments eliminate a lot of comments that weren't providing a lot of value and if anything were something additional we'd have to keep up to date and there's a lot of great tools to keep our code organized and comments aren't a great one so clean up those visual markers as you go let's go ahead and move on i thought we'd take a quick second just to review what makes a good comment so we've been going over some bad ones right and oftentimes that's half the battle knowing what not to do often time leaves you with knowing what to do if you've done all the mistakes all you have left are the correct solutions right so what makes a good comment something short and concise something that gets to the point doesn't really have all this fluff in there that's going to you know cause more confusion than anything else something provides value you know does it really give you something at the end of the day or is it just describing what's going on that you can read in you know 20 seconds it oftentimes clarifies code that has a business purpose but will look sort of out of sort and oftentimes in that same scope it will be a warning or ample amplification of its importance and of course legal comments so let's take a look at the code now that we've reviewed that you can see at the top here we have one such legal comment i've had to do these in a couple applications they're not as common as they were in the past that pretty much everyone just uses open source library x y and z but you can see here this uses rs library one point x point x and scrim assumes all risks and doing so comment is mandated by the license you use ros library 2020. this is a legal comment sometimes you have to have that in there just the way it is now as far as our date regex goes do you know what this does i mean i'm not the best at regex i can usually figure it out but i have no idea what this does what this actually does and this is a great example of something that's going to be short and concise but provide value is format a day month month year year that's all this does at the end of the day is it concatenates it validates that this whole crazy regex comes in a couple different days months and years like so that's it it kind of blows my mind to be honest but this is a good example of a comment for when you know there's just something that's going to take an extended period of time to really understand down below here's an example of maybe something that looks a little weird like why are we trimming the string before we do it you might have a comment here someone might go oh well that's silly maybe we store this in the database correctly but maybe we have an issue where the ui layer is injecting empty characters do not remove trim now another way you can eliminate this comment and we're not going to talk about testing in here but a good unit test would actually have this in the unit test to clarify that now you may still remove trim and ignore this comment at some point in time if you think you've solved this but this is very clear about something that's maybe would catch your eye that you're like not quite sure why that's there so here are some examples of some good comments all right so we just talked a little bit about you know what some good comments are i'd like to practice a little bit so our good comments challenge so once you just go ahead and make up use your imagination a little bit and come up with an example legal requirement comment once you also add a comment to the regex here that's somewhat unreadable it's not important what the actual regex does in this case it's the same one as before but just add a comment that you think would make sense in this context and then add a business logic example comment to our function down below go ahead give it a shot all right were you able to do it if not no worries no sometimes when you give a little less instruction people sort of panic a little bit and that's okay um here let's just say for some reason we were using low dash i don't think we have to do this for low dash and we said you know um low dash x no requirement for its use under mit license something like that 2020. whatever you wanted to use as your example legal comment and we have our date right jacks here new format passion yeah we'll do a month month year year a day whatever it is it's not it's not important probably wouldn't be that actually probably month month or day day you're here there we go i don't think the year is ever going in the middle so let's at least make up our unreadable regex comment to be somewhat realistic and then down below here maybe we have you know um temporary password for stage environment right doesn't really matter um but obviously this would look a little suspect here we have three comments that sort of provide value they're good comments in this case they're a little silly because it's a challenge kind of hard thing to write a challenge for but it's important to practice and start looking at this in your code and now you have an example of good comments you have example bad comments and so hopefully you'll use comments sparingly but this is a nice little challenge to remind you of what's a good one all right so we have a final challenge for you and hopefully you might have seen this coming the best challenges are ones that you go and challenge yourself and that's kind of what this is about go to your old projects the ones that you wrote when you're first getting started and haven't looked at for a year six months maybe three months whatever it is go and see if you can apply some of these clean code principles go in there and update those old projects i do it about once every year i go through some of my old repos and i don't change the technologies or anything like that but i do take a look and say how would i make this better and i like doing that to see if i improved and go and take these clean code principles and apply them to all your projects and have some fun with the same thing with algorithms go and if you have some algorithms practice some of these clean code principles on those and review them and maybe you'll see some stuff of how you can even refactor them as you go if you are paired up on a team start implementing these in your code reviews and pair programming sessions or if you're just contributing open source it's a great way to start practicing this and start looking for it when you do these code reviews and you pair a program so that not only you get better but you improve those around you as well last but not least go and join the scrimba discord channel if you're not already a member and go and share your before and afters in the i built this group a lot of great stuff there you know one of the things i like about teaching and mentoring and things like that is helping people improve and helping people learn and motivating people and you can do that too by just going to the discord channel and showcasing what it is you're doing and you know people will be able to relate and being like oh i'm at the same spot i'm glad to see someone who's one spot ahead of me succeeding and so on and so forth but definitely go and do all these things this is your final challenge quite a bit quite a bit for you to do but the thing that you have to remember is what makes scrimba so great or one of the many things that makes scrimmage so great is that active learning and this is an extension of that i want you to be very active and if you are you'll retain what's here you know write clean code and you'll start coding like a pro before we talk about what's next i just want to say again congratulations for finishing the course a lot of people don't make it to the end of the course you should feel very proud and i hope by the end of this course rather i know by the end of this course you have learned at least one thing that you can then go and apply and level up your coding game that's why i sort of affectionately have called this course code like a pro because clean code is just one aspect of being a professional software engineer in my opinion and i wanted to really make that clear so what's next right well if you remember when we started this course we had three main objectives making our code more searchable readable and understandable you can make yourself a little bit more able by making things testable and automatable sometimes you have to discover these things on your own but i'm going to give you a place to start how might we accomplish some of those objectives well we just did some clean code practices we're going to talk a bit about unit testing in a future course a little hint but i look forward to an introduction to unit testing course by your boy integration testing would be another thing that you could go and look into we talked a little bit about linters adding them to your code bases and using them so that you can make things more automated similar to what we're trying to do with our unit tests and integration tests git hooks husky is an npm package that will fire off some of these scripts that you have anytime you do a commit or you do a push that will make it so that it will link your files if it can or even spell check our files which is what the c spell package here i recommend is i also recommend to make it easier on yourself by configuring your text editor i use vs code to auto save auto format auto lint all that sort of stuff most our editors are very powerful and with extensions can do a lot of this stuff for us so that we don't have to think about every minute detail and of course look into more advanced items like the solid principles some additional resources that i'd highly recommend if you want to dive deeper in clean code clean code came about from uh not entirely but from uncle bob robert martin he has this wonderful book here called clean code a handbook of agile software craftsmanship and i'd highly recommend that you look into that the examples there are in java but i don't think that's too much of an issue but i also have this clean code javascript repo which you can click here which if i remember correctly uh ryan mcdermott who i think was a google engineer took the examples from clean code and created a free npm repo and did javascript examples so you can check that out if you want to dive deeper into clean code stuff last but not least i want you to share in the phone on discord scribba has a fantastic community of all their students and creators like myself that go through there lots of great fun over there you can click this link and join them but again guys thanks so much for taking this course thanks so much for being part of the dev community and congratulations on finishing it i look forward to seeing some of your successes in the scrimba discord channel
Original Description
🎓 View our courses: https://scrimba.com/links/all-courses
Learning clean code is one of the best career investments you can make. By spending one hour to learn the fundamentals, you get to reap the benefits across all your future code bases. It's 10x the payoff for the effort.
In this course, professional developer and coding Youtuber Dylan Israel takes you through some top tips to help you polish your code, making it more professional, easier to read and understand, and less prone to bugs.
In just one hour, you’ll cover how to improve your variables, functions, comments, and more! By the end, you’ll have the knowledge to improve your existing and future projects and ensure that your code is as searchable, readable and understandable as possible.
✨ Contents: ✨
00:00 - What is clean code?
04:35 - What is a linter?
07:01 - Clean variables in JavaScript part 1
09:00 - Clean variables in JavaScript part 2
12:23 - Clean variables Challenge
16:06 - Clean variables & Clean Properties (Challenge)
18:02 - Clean variables: Magic Numbers 🧙
21:50 - Clean variables: Magic Numbers (Challenge) 🧙
23:43 - How to organize your code: spacing and returns
25:35 - Clean functions in JavaScript
26:43 - Clean functions: Limit parameters
28:19 - Clean functions: Naming & standardization
30:31 - Clean functions: Naming and standardization (challenge)
32:47 - Clean functions: Encapsulating conditionals
37:20 - Clean functions: Encapsulating conditionals (challenge)
39:48 - Good comments in JavaScript
43:47 - Avoiding comments with refactoring
47:20 - Avoiding comments with Git
48:53 - Clean comments: Avoid visual markers
51:30 - Clean comments: Avoid visual markers (challenge)
53:01 - What is a good comment in JavaScript?
53:00 - Good comments (Challenge)
58:32 - Clean code: Final challenge 🤺
01:00:56 - Clean code: What's next? 🤔
💫 Try this course on Scrimba
https://scrimba.com/learn/cleancode
💻 Check out Scrimba’s interactive learning platform:
https://scrimba.com/
🌲 Linktree
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Scrimba · Scrimba · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
CSS Grid Course: Learn the Basics in 3 Minutes
Scrimba
CSS Grid Course: Positioning Items
Scrimba
CSS Grid Course: Why Learn It And How It Compares To Bootstrap
Scrimba
CSS Grid Course: auto-fit & minmax
Scrimba
CSS Grid Course: Implicit Rows
Scrimba
CSS Grid Course: Fraction Units And Repeat
Scrimba
CSS Grid Course: Justify Items and Align Items
Scrimba
CSS Grid Course: An Awesome Image Grid
Scrimba
CSS Grid Course: Named Lines
Scrimba
CSS Grid Course: auto-fit vs auto-fill
Scrimba
CSS Grid Course: Justify Content and Align Content
Scrimba
CSS Grid Course: Template areas
Scrimba
27. Setting up the structure - Responsive CSS Tutorial
Scrimba
25. Making the navigation responsive - Responsive CSS Tutorial
Scrimba
36. Playing with the title's position and negative margins - Responsive CSS Tutorial
Scrimba
31. Starting the CSS for our page - Responsive CSS Tutorial
Scrimba
26. Taking a look at the rest of the project - Responsive CSS Tutorial
Scrimba
15. Spacing out the columns - Responsive CSS Tutorial
Scrimba
33. Starting to think mobile first - Responsive CSS Tutorial
Scrimba
22. Making our navigation look good - Responsive CSS Tutorial
Scrimba
37. Changing image size with object-fit - Responsive CSS Tutorial
Scrimba
44. Module Wrap up - Responsive CSS Tutorial
Scrimba
16. Controlling the vertical position of flex items - Responsive CSS Tutorial
Scrimba
39. Setting up the widgets and talking breakpoints - Responsive CSS Tutorial
Scrimba
42. Setting up the About Me page - Responsive CSS Tutorial
Scrimba
35. Changing the visual order with flexbox - Responsive CSS Tutorial
Scrimba
23. Adding the underline - Responsive CSS Tutorial
Scrimba
21. Using flexbox to start styling our navigation - Responsive CSS Tutorial
Scrimba
20. Creating a navigation - Responsive CSS Tutorial
Scrimba
40. Using a new pseudo class to wrap up the homepage - Responsive CSS Tutorial
Scrimba
43. Fixing up some loose ends - Responsive CSS Tutorial
Scrimba
32. Starting the layout. Looking at the big picture - Responsive CSS Tutorial
Scrimba
24. A more complicated navigation - Responsive CSS Tutorial
Scrimba
28. Feature article structure - Responsive CSS Tutorial
Scrimba
34. Styling the featured article - Responsive CSS Tutorial
Scrimba
18. Making layout responsive with flex direction - Responsive CSS Tutorial
Scrimba
19. flex direction explained - Responsive CSS Tutorial
Scrimba
41. Creating the recent posts page - Responsive CSS Tutorial
Scrimba
17. Media Query basics - Responsive CSS Tutorial
Scrimba
30. Home Page. HTML for the aside - Responsive CSS Tutorial
Scrimba
38. Styling recent articles for large screens - Responsive CSS Tutorial
Scrimba
29. The home page. HTML for the recent articles - Responsive CSS Tutorial
Scrimba
10. ems and rems an example - Responsive CSS Tutorial
Scrimba
1. Starting to think responsively - Responsive CSS Tutorial
Scrimba
4. Controlling the width of images - Responsive CSS Tutorial
Scrimba
5. min width and max width - Responsive CSS Tutorial
Scrimba
3 CSS Units. Percentage - Responsive CSS Tutorial
Scrimba
11. Flexbox refresher and setting up some HTML - Responsive CSS Tutorial
Scrimba
12. Basic Styles and setting up the columns - Responsive CSS Tutorial
Scrimba
8. The Solution Rems - Responsive CSS Tutorial
Scrimba
14. Setting the columns widths - Responsive CSS Tutorial
Scrimba
2 CSS Units - Responsive CSS Tutorial
Scrimba
7. The problem with ems - Responsive CSS Tutorial
Scrimba
6. CSS Units. The em unit - Responsive CSS Tutorial
Scrimba
13. Adding the background color - Responsive CSS Tutorial
Scrimba
9. Picking which unit to use - Responsive CSS Tutorial
Scrimba
Tutorial to Learn Alpine JS - Full Course for Beginners
Scrimba
Guide To Algorithms in Javascript [Binary Search] - Full Course / Tutorial
Scrimba
Learn UI Design [7 Fundamentals Tutorial] - Full Course for Beginners
Scrimba
Javascript Tutorial for Beginners [From 0 to ES6+] - Full Course
Scrimba
More on: API Design
View skill →Related Reads
📰
📰
📰
📰
The QUALIA concept may be distracting us from the true ‘hard problem’
Medium · AI
The UN says AI is moving faster than the rules, and it has a report to prove it
The Next Web AI
How I’d Go From Security+ to AI Red Teaming
Medium · Cybersecurity
Why No One Really Understands AI, And Why That Should Worry Us
Forbes Innovation
Chapters (24)
What is clean code?
4:35
What is a linter?
7:01
Clean variables in JavaScript part 1
9:00
Clean variables in JavaScript part 2
12:23
Clean variables Challenge
16:06
Clean variables & Clean Properties (Challenge)
18:02
Clean variables: Magic Numbers 🧙
21:50
Clean variables: Magic Numbers (Challenge) 🧙
23:43
How to organize your code: spacing and returns
25:35
Clean functions in JavaScript
26:43
Clean functions: Limit parameters
28:19
Clean functions: Naming & standardization
30:31
Clean functions: Naming and standardization (challenge)
32:47
Clean functions: Encapsulating conditionals
37:20
Clean functions: Encapsulating conditionals (challenge)
39:48
Good comments in JavaScript
43:47
Avoiding comments with refactoring
47:20
Avoiding comments with Git
48:53
Clean comments: Avoid visual markers
51:30
Clean comments: Avoid visual markers (challenge)
53:01
What is a good comment in JavaScript?
53:00
Good comments (Challenge)
58:32
Clean code: Final challenge 🤺
1:00:56
Clean code: What's next? 🤔
🎓
Tutor Explanation
DeepCamp AI