My 10 “Clean” Code Principles (Start These Now)

  Рет қаралды 111,059

Conner Ardman

Conner Ardman

Күн бұрын

Writing "clean" code is oftentimes described as one of the most important aspects of programming and software engineering, but how do we even do that?
Prepping for your frontend interviews? Use code "conner" for a discount on my product FrontendExpert:
www.frontendexpert.io/conner
🎬 TikTok: / connerardman
💼 LinkedIn: / connerardman
💻 Video/Coding Gear (affiliate): www.amazon.com/shop/connerardman
Timestamps
0:00 Principle #1
2:16 Principle #2
4:05 Principle #3
5:37 Principle #4
7:14 Principle #5
8:37 Principle #6
9:28 Principle #7
10:41 Principle #8
11:57 Principle #9
14:00 Principle #10
Business/brands 👉 youtube@connerardman.com

Пікірлер: 134
@euqinuykcaj
@euqinuykcaj 2 ай бұрын
I like the first sentence I hear after clicking your video is "The first principle of clean code ..." just jump to the point. Love it!!!
@ConnerArdman
@ConnerArdman 2 ай бұрын
Turns out people can read the title and don’t need videos to introduce it for 2 minutes! What a novel concept 😂
@sidouglas
@sidouglas Ай бұрын
0:00 1. Eliminate if/else branching; early termination 2:16 2. Ambiguous definitions: ‘is’ function prefix to denote boolean return 4:05 3. Self documenting code: avoid belaboured comments 5:37 4. Consistent formatting. Use Eslint + Prettier to automate code style 7:14 5. DRY business logic. Look for opportunities to refactor. Make sure to test! 8:37 6. Fail or exit functions fast. Related to 1. 9:28 7. Avoid magic values - declare and use CONSTANTS instead. 10:41 8. Avoid violating single responsibility. Prefer to use pure functions (no side effects) 11:57 9. Overly clever code (code golf). Leads to impenetrable single liners (have to rewrite in order to debug) 14:00 10. Premature optimisations.
@brunofilgueiras3518
@brunofilgueiras3518 Ай бұрын
thanks for the summary buddy
@codycortello
@codycortello 9 күн бұрын
1. Is also called Guard Clauses or reducing nesting
@R1pTheJacka
@R1pTheJacka 2 ай бұрын
This might be the first KZfaq video I've seen in well over a decade where the content actually starts at 0:00 Subscribed
@kresuu3567
@kresuu3567 2 ай бұрын
For real LOL it's refreshing to see
@davidmartensson273
@davidmartensson273 2 ай бұрын
The isPrime example, you use Math.sqrt in the condition, this will in many languages, including js, cause the sqrt to be calculated on each pass of the loop so you should break that out to a variable and the comment can then be added to the creation of the variable, this will make it even more clear that the comment is for why we use Math.Sqrt and improve performance and reduce line complexity since the loop conditional will be a simple i
@ConnerArdman
@ConnerArdman 2 ай бұрын
Good call, putting the smart in Smartensson
@davidmartensson273
@davidmartensson273 2 ай бұрын
@@ConnerArdman the s is actually from my real middle name and I never realized it was part of the visible name :D.
@BangsarRia
@BangsarRia 2 ай бұрын
Try to convert comments to names. For example, name the variable nonPrimeWillHaveFactorBelow and assign 1 + the Sqrt.
@Ssek16
@Ssek16 2 ай бұрын
You made me realise that my JavaScript code was complete doodoo and made me redo it all again. This time I actually understood what I was trying to do. Thank you.
@ConnerArdman
@ConnerArdman 2 ай бұрын
That’s awesome 🙌
@yt.Interest
@yt.Interest Ай бұрын
W, no bullshit, no annoying stuff, straight forward, not only clean code, also clean video
@kikocastroneto
@kikocastroneto Ай бұрын
This video is an excellent example of what uncle Bob mentioned in his book about being pragmatic with your own clean practices. All your tips are in the book, and the tips you don’t judge it to be good you just don’t have to use. People flame uncle Bob with the “functions shall be short” tip, but they forget the pragmatism mentioned by Bob in the introduction of the book.
@AntonioSantos-ve6zv
@AntonioSantos-ve6zv 2 ай бұрын
Though of skipping the video, but it immediately got my attention due to how objective it is. Thanks for the content.
@iqbalibrahim4713
@iqbalibrahim4713 24 күн бұрын
Really love your content, straight to the point with examples 👍🏻
@pH7Programming
@pH7Programming 25 күн бұрын
Always great reminders. Keep up the hard work! 💪
@jhontriboyke5534
@jhontriboyke5534 2 ай бұрын
the if else principle really help me, sometime i was confused why my else block code didnot work. thank you
@anthonysetiadi
@anthonysetiadi 2 ай бұрын
This video is so good. So many gold nuggets that you don't learn in traditional coding bootcamps or tutorials.
@ConnerArdman
@ConnerArdman 2 ай бұрын
Glad you enjoyed it! 😀
@christopheanfry2425
@christopheanfry2425 2 ай бұрын
Thank you so much this is gold!!!
@scrapsplaysgames
@scrapsplaysgames 2 ай бұрын
Just a small addition on the example of DRY; what's covered here is to replace three functions that do the same thing with one function that can do anything. If you want to enforce the passed-in value is always one of a specific set of strings, it should still be fine to use these other three functions. They can cover an abstraction, enforcing the passed "action" to be a specific value. Such as "return logAction("logged in")" in the first example function.
@BangsarRia
@BangsarRia 2 ай бұрын
Regarding Optimization. In more than 20 years writing Production Java code for one of the largest international banks, I have had to optimize my code twice. The first time a change to the XSLT library implementation made processing take 50x longer. Simply adding a line of code to set an undocumented but supported flag returned to normal. The second time, Dodd Frank caused volume to increase 10x overnight. Because I had written the worker code to be reentrant all I had to do was change config parameter # of workers from 1 to 16 to increase throughput 10-fold (and add an extra CPU core and run code analysis and deadlock detection overnight). Bottom line: Just write Clean Code and - as Conner says in the video - let the compiler worry about the insignificant local optimizations that are such tempting distractions; that's its job, not yours.
@SantiiYanez
@SantiiYanez 2 ай бұрын
Amazing video, thanks for this.
@ibunnysaur1
@ibunnysaur1 Күн бұрын
This was excellent in that it's a practical and straightforward explanation, thank you!
@user-dr7yi2fj6x
@user-dr7yi2fj6x 2 ай бұрын
Hello Conner, This is absolutely great advice! Please make videos like this :)
@ConnerArdman
@ConnerArdman 2 ай бұрын
🫡
@eugeneponomarov7429
@eugeneponomarov7429 2 ай бұрын
Great video! Beginners should take a lot of notes from here.
@ronaldpaek
@ronaldpaek 2 ай бұрын
Thank you for this 🙏 ❤🎉
@jazzpants
@jazzpants 2 ай бұрын
Thank you Connor!!! I am forever dealing with "code smells" because people are not taking the time to do clean code. And I always end up cleaning up THEIR mess when I have to do the daily merge of everyone's code. 😭
@MeriaDuck
@MeriaDuck 7 күн бұрын
Try and make it their problem, that is, try to get the teammates to use the same principles as you want to. That way you are less burdened when doing merges and they get their stuff merged with more ease and probably learn from it. Where possible / feasible, use linting and code guidelines to automate the guidance.
@amixengineer
@amixengineer 2 ай бұрын
excellent content thanks Conner.
@Axlefublr
@Axlefublr Ай бұрын
when it comes to quotes (in languages that accept both), I use single quotes generally, unless the string contains a single quote, in which case I use double quotes (I prefer that to escaping).
@mansurhamidov2319
@mansurhamidov2319 2 ай бұрын
Thanks for video! Principle #6: I think you have forgotten to mention about direct returning the value instead of placing it to const and then returning it Principle #7 I think better naming for the second variable would be TAXABLE_TRANSACTION_MULTIPLIER
@tmbarral664
@tmbarral664 Ай бұрын
For the "return boolean" functions, I used "has'" and "can" also, depending on my needs.
@MeriaDuck
@MeriaDuck 7 күн бұрын
Going to use this in my lessons!
@wouterk21
@wouterk21 2 ай бұрын
Great clear video 👍. But to be honest, the majority of the examples are covered by using a good ESLint configuration. Add some Prettier on top for the spacing / formatting.
@2000PhucNguyen
@2000PhucNguyen 5 күн бұрын
I know all your principles, because I have read Clean Code book. But I appreciate this video, and I love this video and your content. +1 subscribe.
@Blafasel3
@Blafasel3 25 күн бұрын
example 1 in Principle 9 is actually rather subtle O(n^2) because the reduce is O(n) and the spreading again is O(n), so its two nested loops. Another reason why the second approach is plain better ;) The second is only O(n), becasue its two consecutive loops.
@albertrain7093
@albertrain7093 2 ай бұрын
Hey Conner) thanks for the useful tips. But something is not clear for me in example with reduce and filter. If I'm not mistaken distructuring in reduce will cause the time complexity Am I right?
@ianfrye8988
@ianfrye8988 Ай бұрын
On #8 I would possibly rename it to calculate circular area or something as "calculateArea" could be for any shape but it only calculates a circle.
@tonymihut3070
@tonymihut3070 11 күн бұрын
Just came across this and immediately subscribed 1 minute in because I need Jesse Eisenberg talking about coding in my life.
@VinOnline
@VinOnline Ай бұрын
I appreciate your videos!
@danielcommins1285
@danielcommins1285 2 күн бұрын
13:14 the reason why the bitwise expression is confusing in that example is because it evaluates to a number, 1 or 0, instead of true or false. Js deals with truthy/falsy for conditional expressions so it still works, but it should really evaluate to a boolean if being used in a conditional, e.g. n & 1 !== 0 Great tips otherwise 🔥
@pizzarand
@pizzarand Ай бұрын
Very nice video mate
@anonymous49125
@anonymous49125 8 күн бұрын
this video slaps. I'm a huge believer that optimization should come only went a bottleneck presents itself, and in all other instances making code that is human readable is paramount. To assume how the code will be ran on the hardware, especially in javascript of all things, and attempt to pre-optimize is a fools errand. What is vastly better is easy to digest at a glance human readable code, where you can intuit how it should be used and how it can use extended and maintained. Great stuff!
@weroro
@weroro 27 күн бұрын
5:37 I use a combination. If I have variables at the beginning or end of the string, I don't use ${var} but var + or + var because that's two less character [4 chars VS. 2 chars]. If it's variables inside a string, it's more effective to use ${var} because it's less characters than using " + var + " [4 chars VS. 5 chars]. 8:37 I use if(variable?.trim?.()) [ I know it's not bulletproof because an object with a trim() method might come in, but in many cases it's legitimate to use my way, especially if I've tested somewhere before that it's not an object. ]
@gnack420
@gnack420 9 күн бұрын
The number of characters makes absolutely no difference to the effectiveness of the code.
@Bingo901
@Bingo901 Ай бұрын
In Principle 3 you should also extract Math.sqrt so it wont call it again and again at each iteration
@EnzoAuditore
@EnzoAuditore Ай бұрын
Thank you for this
@Micosek98
@Micosek98 2 ай бұрын
#1 Mostly agreed, but I think the last part when there are two ways of ending function, one with return and the other one with no return is more confusing than just one else statement #4 There was a semicolon missing in one line ;)
@ConnerArdman
@ConnerArdman 2 ай бұрын
Yeah that’s valid. Or if there is going to be a return, it should have been an empty return in hindsight.
@KeithKazamaFlick
@KeithKazamaFlick 2 ай бұрын
thanks...this helped
@santra528
@santra528 2 ай бұрын
Now a days, I write the code and get my code reviewed by AI to see if there can be any potential improvements or refactoring we can do in terms of clean code and it helps me to write clean code. Anyways these tips are really golden! A lot of times I make these mistakes and get review comments from my Tech lead about these mistakes
@CallousCoder
@CallousCoder 2 ай бұрын
AI is very very bad at clean and efficient code! I used CODY for code smells and it doesn't even see context it says: "check that pointer" and I always go: "check line xyz for your remark number x" And it sees it's covered. It comes up with idiotic ideas of naming variables really long like n "number" for readability. For fuck sake, it's the only parameter in the function, the type says its an u64 what else do you want, Cody? I am not going to type number everytime :D So my advise is, be very critical because AI is really really bad at coding!
@codeSurvivor
@codeSurvivor Ай бұрын
Nice video, thanks! Straight to the point! In principle 9, I think that the example was not very good regarding the 2 loops VS 1. Reduce can be a little hard to get used to, but once you do, it's really easy to read and understand what it does. I used to chain array functions as you did here, but mainly because I never took the time to work with reduce. Now it's just easy, and if you have big arrays, loop twice VS once is really not a good idea.. I agree thaw trying to be clever while programming does not make sense, but reduce is just a basic array operator 🤷🏻‍♂️
@AnkitGarg
@AnkitGarg Күн бұрын
Nice content, good job. The first tip is a double edged sword. Too many control statements can also be confusing. You have to check the entire method to understand what all it can return. Sometimes the if-else blocks which populated a variable and return at the end is easier to understand.
@tomz4332
@tomz4332 2 ай бұрын
Try ESLint & Prettier & JSDoc
@abdelrhmanmohamed4754
@abdelrhmanmohamed4754 2 ай бұрын
Hi i have a question , how much JavaScript enough to start react js im should i build big projects with js or just simple projects
@telephonedude
@telephonedude 2 ай бұрын
Couldn't agree more with all of these, though Python has instilled a habit of using 'SINGLE_QUOTES' for constants and identifiers, and "double quotes" for misc./ "natural" text in me
@th3ja
@th3ja 2 ай бұрын
Amazing 💯
@malvoliosf
@malvoliosf 2 ай бұрын
You aren’t going to comment on the square-root being calculated on every iteration (5:35)?
@MeriaDuck
@MeriaDuck 7 күн бұрын
Example number nine does not have to be two loops, a compiler can reason about this and just make one reduction for it.
@michaldivismusic
@michaldivismusic 17 күн бұрын
I wish more people used principle #2
@asoronite
@asoronite 2 ай бұрын
very good, thank you
@jfedererj
@jfedererj Ай бұрын
I always eye-roll at reduce being labelled "hard to read". Maybe don't dump it all in one line?
@SalTarvitz
@SalTarvitz Ай бұрын
Very nice logic.
@sagecole8055
@sagecole8055 2 ай бұрын
Over commenting. I’m in university and I have to comment everything line for line and have a massive comment block on the top explaining how it works overall. Why is this taught if that many comments is actually a bad thing?
@ConnerArdman
@ConnerArdman 2 ай бұрын
My guess would be it’s probably for the benefit of the grader to essentially “show your work.” Hard to say for sure though 🤷‍♂️
@lawrencemanning
@lawrencemanning 2 ай бұрын
Actually learning how to comment is a skill that is difficult to teach. Your prof’s approach is likely because he is just a tad lazy, but is also not totally terrible. As long as your comments aren’t just rewording the code, you’re doing ok. Explain the thinking behind it, why a more obvious approach isn’t valid, etc. Have fun!!
@morchellemusic2829
@morchellemusic2829 4 күн бұрын
Nice, thanks
@zigajavornik1026
@zigajavornik1026 2 ай бұрын
I program PLCs and I had an argument with a coworker stating magic numbers are the way to go, I was so pissed, my industry is so outdared...
@mentoriii3475
@mentoriii3475 2 ай бұрын
what i like to do is convert a null or undefined value into a boolean value, in this case if(!user)
@VLADICA94KG
@VLADICA94KG 7 күн бұрын
at 2:00 you are missing return statement.
@PedroCouto1982
@PedroCouto1982 12 күн бұрын
Suggestion: It's a very good useful video, but instead of “Principle #n” for the names of the timestamps, it would be more useful if they were meaningful names. I like to read the description and jump to specific topics. @sidouglas did something similar. It can be more succinct. For instance, instead of “Eliminate if/else branching; early termination”, it can be “Guard clauses” or “Return early”.
@darknight3613
@darknight3613 2 ай бұрын
For 9:33 i would say that it would be clearer if we did: "let price = 10.0" so we know it is double
@user-zj2si7md6q
@user-zj2si7md6q Күн бұрын
I just watched first part of the video, u removed if else and added more ifs, the pronlem with your code style is that when it will come to priority of your ifs, because just swap two of them and your code does not work as expected, it mean if i have 10 ifs i should keep in mind not to change the order od ifs in future when i add or remove a condition, good video and thanks for sharing but who made if else knew better than us if not they just made if without else.
@claushellsing
@claushellsing Ай бұрын
You should have your own eslint rules
@AndersBaumann
@AndersBaumann 2 ай бұрын
Good examples. But using exceptions in validation code will throw a lot of exceptions in a large system. They will clutter the application monitoring and hide the actual problems. In addition, exceptions are expensive. Invalid user input is expected.
@memeproductions4182
@memeproductions4182 2 ай бұрын
so what should you instead of throwing?
@Aedaeum
@Aedaeum 2 ай бұрын
@@memeproductions4182 Validation should be handled by usually telling the user what went wrong, which means not throwing an error, but rendering some kind of message to the user (sending JSON response, printing to screen, etc...); it doesn't make sense to crash your application because of invalid user input lol. But to be fair, all of his examples are oversimplifications for the sake of teaching a specific concept, so we can cut him some slack.
@sebastienollquist1318
@sebastienollquist1318 Ай бұрын
First programming video I see done by Michael Cera
@typoilu3413
@typoilu3413 2 ай бұрын
For the first principle, inverting if..else only works in general with if..else throw or if..else return) but in most cases it will make everything worse. Here are some tips to keep track of what clause brackets corrsepond to -corresponding bracket have the same color on vscode you can clearly see it on the video. Maybe with another color theme they would be more visible -there is a keyboard shortcut to go from a closing/opening bracket to the corresponding opening/closing bracket -when your mouse is over a bracket the corresponding one will be highlighted .
@asdqwe4427
@asdqwe4427 2 ай бұрын
I'm sure you can find a bunch of cases where this isn't optimal. But generally speaking, the important part of what he is demonstrating is that getting much of the validation out of the way right at the beginning of the function makes the rest of the code much more readable. The return statements on the bottom are ambiguous, but those are not the main point of the principle
@soniablanche5672
@soniablanche5672 2 ай бұрын
2nd one can be solved by using jsdoc
@da40au40
@da40au40 2 ай бұрын
For the first example, in cases where you have to log all exceptions, you'll really need nested if else.
@CallousCoder
@CallousCoder 2 ай бұрын
Generally I do agree, just some things I would argue against. The second example the variable isn't ambiguous you see the .length before it so it obviously is length. Frankly I don't really care for variable names, I come from a time where variables were often just memory addresses unless you had an assembler. I love the golang single letter variable idioms, like I said I coded so much assembly I really don't care about variable names. Why use a build-in uppercase function? You can easily write that in 1 line yourself and you can handle a decent error as well. And that function name is very verbose a toUpper is enough. But the get is actually misleading, as you are not getting something from a class or a struct. This is just a static stand alone function. So arguably toUpper is enough imo. Bitwise operations are no more or less legible then a mathematical approach -- you are not a programmer if you have difficulty understanding bitwise operations imo. I prefer the bitwise operating because it will ALWAYS (despite your compiler or interpreter) going to be fast. With a modulo (division) you never know. Especially if you end up using your code on a small microcontroller that has no division and multiply then no massive maths function is included that perhaps could blow your program beyond the capacity of the memory of the microcontroller. I literally had this happen with a person who wrote a task distributor on two physical machines using a % in Python and it was so slow! I changed it to & and it went from 25 seconds to 7 seconds. Luckily in Python 3 this sort of thing is optimised but that's why you should just stick with binary operations.
@Adiounys
@Adiounys Ай бұрын
You don't see 'length' before it, you see 'const' before it. The whole point is a variable is defined outside of a function and it may not be defined just before it's usage. It's just an example.
@CallousCoder
@CallousCoder Ай бұрын
@@AdiounysI was referring to the function name checkPasswordLength, it implies it’s the number of characters of the password. It’s a very descriptive name already. And having unassigned variables is the death. Especially when you declare those outside of a function. The only types that you may get away with by not explicitly passing in are constants. And even that I’m not a fan off, as it’s not very explicit. Better is to have a configuration singleton and pass that into the function via a parameter. Now a better example here would’ve been: isPasswordMatchingPolicy(string password, PasswordPolicy policy)
@Adiounys
@Adiounys Ай бұрын
@@CallousCoder You wrote "variable". In your example you would still have the 'MIN_PASSWORD' in your policy type so the point mentioned in video is still valid. I such case I would name it simply 'minLength' since the "password" would be implied from the 'PasswordPolicy'.
@CallousCoder
@CallousCoder Ай бұрын
@@Adiounys well usually a password has more parameters than length alone.
@avivshvitzky2459
@avivshvitzky2459 2 ай бұрын
I know these principles, but I can't pass a job interview cause my code solving brain isn't as good as yours XD
@Variant_Delta
@Variant_Delta 2 ай бұрын
Well in code interview it's lame but they dont care about clean code, they just throw you with random interview question which does not represent the job of a developer. Wish you good luck on your next interviews, you got this !
@avivshvitzky2459
@avivshvitzky2459 2 ай бұрын
@@Variant_Delta 🫶
@SomethingSenseful
@SomethingSenseful 2 күн бұрын
Fallowed all 10 principles consistently from last 5 years .. still nobody appreciated 😢
@borasumer
@borasumer 2 ай бұрын
I'd still go with the reduce one and made it more readable 😂
@honkhonkv2236
@honkhonkv2236 2 ай бұрын
The whole #4 point could be fixed with an extntion like prettier, i can't see myself formating my code by myself all day long.
@Tekay37
@Tekay37 16 күн бұрын
Principle 10 is not an argument against "premature optimization", it's an argument for unnecessary pessimization. Premature optimization is when you make the uninformed decision to switch to assembler to squeeze a few CPU cycles out of a function. Premature Optimization is not a thing in purely high level code as you have it in languages like javascript. Unfortunately, this misconception is very widespread and it is leading to incredibly slow code, where the whole codebase is the bottleneck, because everything it pessimized to a point where you can't even find a place to start optimizing. With all the pessimizations stacked on top of each other, we today have the issue that simple operations like starting a program can take 10 seconds and more, where it should take less than half a second.
@EmreDev7-qk7sf
@EmreDev7-qk7sf 5 күн бұрын
so using double equity is best practice (1st example)? While making "clean code principles" video maybe you should also be careful about some easy best practices. use triple equity. because you look like experienced developer, so maybe there are new comers which may think double equity is better in js
@ConnerArdman
@ConnerArdman 4 күн бұрын
For null checks specifically, yes == is by far the more common practice in my experience. This is just for checking against undefined as well. Everything else === though. For example, here’s this exact idea documented in Google’s style guide: google.github.io/styleguide/jsguide.html#features-equality-checks-exceptions
@Andy_B.
@Andy_B. 2 ай бұрын
👍
@ohcrap2222
@ohcrap2222 Ай бұрын
Nothing against the Conner but I hate JavaScript, just having the variable type and return type speaks volumes.
@rzGameDev
@rzGameDev 2 күн бұрын
"easy to understand" vs. "more performant" while I agree, creating code that is complex for the sake of convolution is bad. I am not in agreement with easy to understand code should be used over performant code. Just comment your complex functions or lines stating what it does. In applications that are running 100s or 1000s of actions these things don't really matter. When you're running millions of actions asynchronously sometimes milliseconds matter.
@KunglawAdy
@KunglawAdy 2 ай бұрын
so basically clean code made a code looks like python as possible ? haha iam joking nice content about clean code
@LokiDaFerret
@LokiDaFerret 2 ай бұрын
LoL. In your first example you actually alter what the code does. So I think I'll take the rest of your video with a grain of salt. I'm really surprised I haven't seen a comment that refers to this.
@ConnerArdman
@ConnerArdman 2 ай бұрын
The code does the exact same thing…
@LokiDaFerret
@LokiDaFerret 2 ай бұрын
@@ConnerArdman your new result will return whatever value is returned from your underage function (if it executes). The original did not return anything. So always returned null
@ConnerArdman
@ConnerArdman 2 ай бұрын
Ah yeah that’s what you meant. There’s a note in the video that I shouldn’t have done that and should have just used an empty return or left the final if/else 👍
@LokiDaFerret
@LokiDaFerret 2 ай бұрын
@@ConnerArdman if it were me I would have used the if else shorthand syntax with colon :. Anyway glad we got that sorted. 👍
@MrSpongeHead
@MrSpongeHead Ай бұрын
Turned the video off as soon as I saw he was using == and not ===.
@ConnerArdman
@ConnerArdman Ай бұрын
== for null checks === for everything else This just ensures you check for undefined as well, and is generally the preferred practice of most style guides / tech companies.
@MrSpongeHead
@MrSpongeHead Ай бұрын
@@ConnerArdman it's better to have clearer code than rely on the odd behaviour of !=. So if (user.age !== null && user.age !== undefined) { } or if (user.age) { } are better options.
@ConnerArdman
@ConnerArdman Ай бұрын
It's really a matter of opinion, but I would disagree. Some prefer explicit checks for undefined, but personally I find it to just be a little clunky. It's also just easy to forget to also check for undefined, whereas eslint can remind you to always do == null to solve for that problem. The industry is somewhat divided on this, but every team I have ever worked on at tech companies big and small preferred == null. As an example, here' is Google's JavaScript style guide stating the same opinion: google.github.io/styleguide/jsguide.html#features-equality-checks As for the second option, I actually think this is an objectively bad practice and one I have seen cause real bugs in production. For example, your check of if (user.age) is presumably meant to be the same as above, to check that the value exists. However, what if the age is 0? 0 is falsy, so we wouldn't get into the if check. In some instances this may be what you want, but in others it isn't. I would generally avoid relying on truthy/falsy for this reason, as even if it is what you want, it is isn't particularly obvious and readable code.
@sidouglas
@sidouglas Ай бұрын
Prefer wrapping loose equality operator in a function: `isNullish` - quite popular in TS. Then it's clear to team you intend ==, rather than being questioned at code review time or eslint squawking at you (eqeqeq rule)
@MrSpongeHead
@MrSpongeHead Ай бұрын
@@ConnerArdman if you're reading from the DOM this isn't an issue as you'll always get a string, otherwise in my opinion it's better to be explicit and check for null and undefined.
@TroyNiemeier
@TroyNiemeier 2 ай бұрын
Strongly disagree with Principle #1, for multiple reasons. I know that what you've demonstrated is super common, and I may not be in any majority about this opinion, but there are other ways to limit the number of nested conditions without inverting every function's conditional logic. One of those ways is to abstract some/all of those conditions into a different function for validation, name it as such, and put that function call in an if-condition to neatly replace them. This is smelling like great example of a failure to follow the 'S' of the SOLID principles. The main gripe I have with your first principle is that writing code with inverted/negative logic goes against the essence of your function name. The function name isn't negatively expressed, so neither should the internal logic. Exceptions and invalid value checks should not get primary/preferential treatment before the code for which your function is named. I personally hate when curly brackets are excluded for one-liner conditions, but that's just me. And your abuse of the return statement to shortcut having to use 'else' is just misleading and lazy. Again, if the function name doesn't suggest that it's going to return something, it probably shouldn't, especially if you're returning from a function call that itself doesn't return anything. That's called a wild goose chase for the next programmer to interpret your code. Don't do that, please.
@philliplam2704
@philliplam2704 2 ай бұрын
No you are bad stop coding just go play with Wordpress
@whynot9963
@whynot9963 2 ай бұрын
I agree about your 2 last points, but the early exit is much more readable. Hell, they even made whole language around that principle 😅
@SeanLazer
@SeanLazer 2 ай бұрын
Early exit is way more readable and worrying about SOLID or SRP in a ten line function is a recipe for over designed code that's impossible to actually follow. The control flow and intention of Conner's function is super clear after the changes.
@LudvikM
@LudvikM Ай бұрын
For the love of gods, please use curly brackets even for one sentence...
@helenmachelen4200
@helenmachelen4200 2 ай бұрын
No mid-function returns please
@airpods4
@airpods4 2 ай бұрын
CLEAN CODE, HORRIBLE PERFORMANCE
@BangsarRia
@BangsarRia 2 ай бұрын
This reminds me of when I started a new job at a service bureau for Savings Banks in 1977 and the Head of Programming patiently told me not to make any procedure calls but only use GOTOs, because "when the runtime unit sees a procedure call it has to take two steps back and make a run at it". He added that he knew what he was talking about because he had written the device drivers for the mainframe in COBOL. A lot of people still don't know what Clean Code means. It means that if you want your code to be maintainable then it has to be Clean. Regarding performance, in another comment here I report that in 20 years of production programming I have had to optimize code twice, which required adding one line of code and changing a config parameter.
@MiroslavJahelka
@MiroslavJahelka Ай бұрын
its not code its just javascript :D
9 JavaScript Features You’ve Never Used
19:36
Conner Ardman
Рет қаралды 15 М.
Browser Tier List (For Software Developers)
0:59
Conner Ardman
Рет қаралды 2,1 МЛН
Китайка и Пчелка 4 серия😂😆
00:19
KITAYKA
Рет қаралды 2 МЛН
WHY DOES SHE HAVE A REWARD? #youtubecreatorawards
00:41
Levsob
Рет қаралды 40 МЛН
My Favorite Code "Anti-Patterns" (Break These)
16:52
Conner Ardman
Рет қаралды 47 М.
Coding Lessons New Developers Should Know
5:08
Bankai
Рет қаралды 95
10 Coding Principles Explained in 5 Minutes
5:44
ByteByteGo
Рет қаралды 115 М.
Top 6 Tools to Turn Code into Beautiful Diagrams
3:24
ByteByteGo
Рет қаралды 549 М.
Clean Code Is Killing Your Projects
9:20
Web Dev Simplified
Рет қаралды 141 М.
This VS Code Extension Is 🔥🔥
0:47
Dave Gray
Рет қаралды 1,3 МЛН
SOLID Principles: Do You Really Understand Them?
7:04
Alex Hyett
Рет қаралды 122 М.
Pratik Cat6 kablo soyma
0:15
Elektrik-Elektronik
Рет қаралды 8 МЛН
Не обзор DJI Osmo Pocket 3 Creator Combo
1:00
superfirsthero
Рет қаралды 1,3 МЛН
😱НОУТБУК СОСЕДКИ😱
0:30
OMG DEN
Рет қаралды 3,2 МЛН
How much charging is in your phone right now? 📱➡️ 🔋VS 🪫
0:11