Why I Never Write Long Functions

  Рет қаралды 102,488

Web Dev Simplified

Web Dev Simplified

Күн бұрын

🚨 IMPORTANT:
JavaScript Simplified Course: javascriptsimplified.com
I only write small functions. You may think this means I have a hard line limit on my functions, but actually I think that is a terrible idea. Instead I make my functions so they can be read even by someone with no programming experience.
📚 Materials/References:
Why I Don't Use The Else Keyword: • Why I Don't Use Else W...
🌎 Find Me Here:
My Blog: blog.webdevsimplified.com
My Courses: courses.webdevsimplified.com
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/WebDevSimplified
CodePen: codepen.io/WebDevSimplified
⏱️ Timestamps:
00:00 - Introduction
01:10 - What Not To Do
02:25 - How To Use Small Functions
03:39 - Small Function Benefits
05:50 - How To Refactor To Small Functions
08:19 - Gotchas
#SmallFunctions #WDS #CleanCode

Пікірлер: 440
@Stoney_Eagle
@Stoney_Eagle 3 жыл бұрын
This is how you write code without comments. It's self explanatory.
@joe-un1ky
@joe-un1ky 3 жыл бұрын
I always thought lots of comments in an app was a bad sign. It very often means your code itself isn't readable.
@wasd3108
@wasd3108 3 жыл бұрын
that function is the comment by itself tho, if you don't make a new function out of it and add a comment that says what the function name would be, you end up with the same thing?
@thedoublehelix5661
@thedoublehelix5661 3 жыл бұрын
@@wasd3108 yes exactly
@markmanning2921
@markmanning2921 3 жыл бұрын
self documenting code is a lame excuse to not comment your code. If you have thought about your code long enough to explain it to someone else you have thought about it long enough to code it. However, anonymous blocks nested to the umpteenth level with no comments what so ever is a C coding standard.
@skaruts
@skaruts 3 жыл бұрын
@@wasd3108 Not really. The difference is also in the content of certain functions where the code becomes much simpler and straightforward to understand. Take the example of the video, in the refactored version of *linkContactAndItem.* The refactored version is glaringly understandable, even for someone like me who doesn't know crap about what that code is for, but I can still very easily understand what it does.
@Tekay37
@Tekay37 3 жыл бұрын
an extra benefit of those tiny functions: You can test all those aspects individually and then write a single integration test for the function that uses the stuff. Those unit tests will be very fast, very specific, and will fail for 1 reason only.
@trappedcat3615
@trappedcat3615 Ай бұрын
Do one-liners like this really need testing, though. I guess it depends, but here it just means more unnecessary tests.
@KaroCodes
@KaroCodes 3 жыл бұрын
Devs often forget to update comments when changing what a function does. Best way to avoid it? Don't write comments! Just write your code in a way that doesn't need them. Just like Kyle does 😁
@WebDevSimplified
@WebDevSimplified 3 жыл бұрын
I couldn't agree more.
@pastagaz4241
@pastagaz4241 3 жыл бұрын
Agree. If your code is readable/understandable, comments are useless. Most of the time, lot of comments == unreadable code
@nowyouknow2249
@nowyouknow2249 3 жыл бұрын
Every function should have a doc string description of what it does atleast according to pep8 in python
@berylliosis5250
@berylliosis5250 3 жыл бұрын
@@nowyouknow2249 That's reasonable for public APIs, especially ones with narrower contracts (in compiled languages, that only applies to narrowed contracts that can't be expressed at the type level); for private functions it's case by case (and they certainly need much less documentation). PEP8 can say what it wants, but readable code usually requires conscious effort
@IndellableHatesHandles
@IndellableHatesHandles 3 жыл бұрын
That's a pretty dumb idea, in my opinion.
@travcurt
@travcurt 3 жыл бұрын
As someone new to coding, I have began to code like this because my functions were getting to large for me to remember what I was doing at the start. >_< And I noticed that as I built another function, I would be copy/pasting parts from other function. So I split those parts out into smaller functions to use in multiple larger functions (which I assume is common practice and the whole point of functions). Great video to help me actually understand (and justify) what Im already doing!
@arjix8738
@arjix8738 3 жыл бұрын
Hmm, that's what we call functional programming iirc. I never agreed with it, like, yeah It's nice to split the code into functions, but that term refers to doing it everywhere. It is a bad idea to be on only one side (Functional Programming vs Object Oriented Programming) I just go for a mix of both, honestly I can't understand those that only go for one side. PS: Functional Prgramming is to have one function only do one thing. Kinda what this video showed, but that is bad practice in a lot of cases, I'm not saying that one function should have everything, but one function could do more than one thing. And OOP is to have objects for anything that could be an object. I really don't understand why you can't use both, sometimes people are dumb.
@daaa57150
@daaa57150 3 жыл бұрын
@@arjix8738 That's not what functional programming is, not at all. Having one function do one thing is just respecting the single responsibility principle at function level.
@arjix8738
@arjix8738 3 жыл бұрын
@@daaa57150 now that I did a google search, yeah, thats right welp, before doing a google search what I knew was from extremists that like to talk about these subjects
@BreetaiZentradi
@BreetaiZentradi 3 жыл бұрын
7 +-2. On a good day you can remember 5 to 9 items. That can be items in a line of code, lines of code in a function or number of items in a menu.
@mikepennington8088
@mikepennington8088 8 ай бұрын
Here is some advice from someone who has been in the profession for over 40 years. Please IGNORE anyone who has a magic, one-size-fits-all solution. Therein lies the path to trouble. That said, he, and you are not wrong but you both generalize too much. The one-liner functions do make sense if you are doing the same thing over and over again in multiple places. If not, just insert the code in place and document the logic with a good comment. Here's the thing: if you have a function that tests a single value and returns a boolean result which is then tested by the caller, you are slowing down the execution for no good benefit. Firstly you are adding overhead to jump into and return from the function, Secondly, you are making TWO tests to get one result. If the language allows the function to be in-lined, then you eliminate the call/return overhead but not that of the extra test. As far as overall function size, I found that that would vary a lot depending on the function. The approach that worked for me is that If I could not easily conceptualize what a function did then it was too complex and needed to be divided into smaller functions that each performed a single task. By single task, I do not mean single step. As an example, your function for getting into your car would be something like Remove key from pocket Insert key into lock ( its is an old car with manual locks ) Turn key Activate latch Pull door open All of the above are simple enough to be steps in the one function and not separate functions. Note that if this was an outline for your robot to do the job, each step becomes complex enough to become a separate function or set of functions. One final thought. Get the code that implements your idea written and then look it over and turn chunks of code that do the same thing into functions. Second, see if you can rearrange the logic to remove steps. If you are doing the same thing in all paths through the function, that should be done once either before the paths split or after they merge. THIS IS ONE BIG REASON THAT A FUNCTION SHOULD ONLY HAVE ***ONE*** RETURN AT THE END.
@adambickford8720
@adambickford8720 3 жыл бұрын
If you're adding white space to 'organize' your function then each 'block' is probably a concept that deserves a name and would benefit from being refactored into a helper function.
@joe-un1ky
@joe-un1ky 3 жыл бұрын
I really like this way of looking at it
@alister_
@alister_ 3 жыл бұрын
I disagree. Most of the time, a function may have some common sections: guards sections, a data section (where you define some variables/constants), a "main" section, and may have a return section. I separate those with a space. It really helps for visual scanning. Also using some kind of "ascii-art-ish" comment may help! Plus, can make the code more aesthetically pleasing.
@code_lift
@code_lift 3 жыл бұрын
wow, nice. I'll give this a shot. Also, great job at showing more personality. You seem more like yourself.
@WebDevSimplified
@WebDevSimplified 3 жыл бұрын
Thanks. I just recorded a video yesterday that I feel really has a lot more personality in it. Hopefully you enjoy it when it releases.
@xiaokourou
@xiaokourou 3 жыл бұрын
@@WebDevSimplified I prefer when you use a more normal voice, not that over the top sing song voice
@tudor414
@tudor414 3 жыл бұрын
It's exactly what I always try to explain to the team. "Write the code to be like a story."
@Ultrajuiced
@Ultrajuiced 8 ай бұрын
Yeah, but not only that. You should also only need to read the cover of the book or a summary if you don't need to know more and not every single page of the book.
@stealthkillertoxic4090
@stealthkillertoxic4090 8 ай бұрын
this is an argument against short functions, you read a story front to back, not 5 lines and then a number that tells you on which page to read the next 10.
@JimRooney
@JimRooney 3 жыл бұрын
Thanks Kyle. I used to go back and forth on this one, but you've really highlighted how it helps. I'm currently working on a rather involved Class object and organized a bit of it this way... and man, you're so right... it's so much easier to read through. I'm sold. Cheers
@Gorgamela
@Gorgamela 3 жыл бұрын
Used to code like this but you'd end up jumping around code and too many functions with half a dozen parameters which becomes hard to follow and a pain to restructure. In theory you should be able to tell by the function name what it does (and it only does one thing) but in practice you still have to look at the function code. Worry less about how long a function is because it's likely going to evolve. Something I found that's actually more helpful is to aim to keep your call stack shallow, i.e. break your program into functions that are called from main and return to main where possible. It reduces complexity / state-space enormously. Doesn't matter how you write your function if it's called from deep in the call stack it's harder to debug than a function called directly from main given the chain of inherited state.
@berylliosis5250
@berylliosis5250 3 жыл бұрын
I think it's easy to get carried away splitting functions like this, and there is a downside: many functions splits the behavior around and actually makes it harder to read. There's something to be said for small functions, but not too small. I don't think the original function here is a problem at all, although the final functions are not a problem either (although they are close to the threshold).
@kaasmeester5903
@kaasmeester5903 8 ай бұрын
It depends on how you are splitting. Splitting behaviour is generally bad (unless it means you end up with a huge function), but splitting across different abstraction levels can be beneficial to readability. In this example, a monolithic function is split at two conceptual levels: 1) how to link an email to an item, by creating a new contact or update an existing one, and 2) how to perform a contact creation or update. At level 1, you care about when records should be created or updated, but not about how exactly that happens. At level 2, you care about the details of record handling, but not about the when or why. When dealing with code, you want to work at 1 or maybe 2 abstraction levels at any one time, and this way of splitting it makes the code easier to understand.
@nordicbastard2328
@nordicbastard2328 8 ай бұрын
I had the misfortune of maintaining an unmaintainable C++ program where the original author was a single-line function addict. It was an absolute mess and impossible to follow as I spent all of my time bouncing around in dozens of different files looking up the objects and their stacks of single-line functions. It was psychotic.
@stephan5512
@stephan5512 3 жыл бұрын
Something that I want to add to your explanation (how I try to write my functions most of the time) is try to implement one behaviour per function (encapsulation). This also helps on deciding better names for your functions, because it is more clear what the function is doing :) I really like the video and the fact that u address code-readability for others or yourself (like when u comeback later to the file and wanna check: how did i implement this logic here again?) Great work man! Love your videos
@filipe_paixao
@filipe_paixao 3 жыл бұрын
You are one of the few guys I can say I love with confidence. thank you for this bro
@jimmorrison2657
@jimmorrison2657 3 жыл бұрын
There is one thing I would change. The name. I think it should be isSmall(a). If it's just small(a), people might think it's a setter method, where you set which value is going to be considered as 'small' within the program.
@pastorfred2543
@pastorfred2543 3 жыл бұрын
Great explanation with plain example. Thanks Sir Kyle
@kirillvoloshin2065
@kirillvoloshin2065 3 жыл бұрын
very clear explanation, thank you! I guess this approach is ideal for our small projects with the possibility of future support.
@gianancheta2955
@gianancheta2955 2 жыл бұрын
I find your channel one of the most helpful resources to learn writing code well!
@wguzman1200
@wguzman1200 3 жыл бұрын
Thank you man, being using this technique lately , and its far better to read and test code now for me event my teammates are starting to using it.
@robertrocker
@robertrocker 3 жыл бұрын
I've been using this way of coding for more over a year and I couldn't agree more. Working with Async code like Rxjs in this way allows you to have extremely readable code that is way easier to test. Awesome content, very good explanation of declarative code! 😃
@pensums
@pensums 3 жыл бұрын
I think this is underated too. Traditional programming teachers also tell their students that the shorter the variable names the better. What it does is everyone is naming their variables super short that it becomes hard to follow what the value is really. That applies to functions naming but also variables in loops. Everytime I bring this up to someone in their forEach loop they tell me it's irrelevant, but it helps me understand the code way faster if I know what is the actual "object" in the loop. I.e. Books.forEach => book.title is way easier to read than x.title if you do just more than printing the object in the console.
@hoanghuy.trannn
@hoanghuy.trannn Жыл бұрын
Who the hell is teaching you that name a var with x, y, z? Nobody.
@holonaut
@holonaut 8 ай бұрын
@@hoanghuy.trannn Maybe it has changed by now, but when I was in uni 10 years ago pretty much every variable was one letter. And the oldschool SQL devs still write t1, t2, t3, t4 in a 60 line statement that joins 4 different tables. It seems sane programming techniques are only taught on the job or by people on YT
@thecodecatalyst
@thecodecatalyst 3 жыл бұрын
Junior dev makes one big function does it all. Senior devs makes small single responsability functions. Great work! You sure know what you are doing!
@stagnudemorte9191
@stagnudemorte9191 3 жыл бұрын
"single responsability"
@dcmbassi
@dcmbassi 3 жыл бұрын
Bow before the God Object!!!
@karanparmar4318
@karanparmar4318 3 жыл бұрын
I am junior dev and this is my 1st year of pro jorney and I don't write everything in one big function, I just wanted to say you gotta stop stereotyping and improvise someone if they are making this kinda mistakes, Whenever I am free I read MR reviews of others and have learnt a lot more about what I never thought of asking.
@jchandra74
@jchandra74 3 жыл бұрын
I feel that it's okay to start with a single big function to start, start "simple" and make it work first, but always refactor to get better human readability afterward, otherwise, you are not really "done". You don't commit the hard-to-read code, you check in the refactored and more readable code :) I've seen production code where I have to be a human debugger at the highest level which is very annoying but it's the reality out there. There more people learning this quicker, the better it is for everyone else that needs to maintain or troubleshoot the product in the long run (including the original author which will probably be clueless on what was going on in the first place when he/she comes back to look at the code after a period of time when troubleshooting something). I've been there myself, not proud of it but I've learned my lesson, hehehe.
@arjix8738
@arjix8738 3 жыл бұрын
@@jchandra74 in my experience i just remember what does what, i dont make comments, but my code is and will always be intuitive for me (it doesnt mean that it is for others)
@ayushdedhia25
@ayushdedhia25 3 жыл бұрын
Hate writing comments while coding? Then write the code as Kyle does...! ❤️ Which makes your code self explanatory 🔥😎
@carl87gt
@carl87gt 3 жыл бұрын
Yep! Comments are a code-smell. Code should be self documenting by method names and clear, concise code. Sometimes you need a comment to explain an odd behavior because of some business rule or legacy integration . . . whatever . . . but generally a lot of commented code means the code probably needs refactoring.
@kadavrgoreman9340
@kadavrgoreman9340 3 жыл бұрын
Hi! Old school still alive! So cool to see! This is how my teacher told me to create a function. 1. Write a multi-line comment with human-readable pseudocode. 2. Make it as straightforward as possible. 3. Create a simple procedure for each line. 4. Change the pseudocode to the call stack. 5. ??? 6. PROFIT! And now I watch this video and feel nostalgic. Thanks a lot. Health and prosperity to you, Kyle.
@nemesioansorin
@nemesioansorin Жыл бұрын
Correct on many instances but 'never' is a too radical word here. For example I need to check and return on realtime some values for a specific container on DOM : width / height / top + pageYoffset + clientHeight + top-bottom-borders / left + pageXoffset + clientWidth + left-right-borders in order to update positions for 2 absolutely positioned elements. One log function solved this the fastest than smaller functions passing arguments to each other - no return since that is the function which updates the DOM directly. Sometime you had to generate / build objects with multiple properties.
@yamogebrewold8620
@yamogebrewold8620 3 жыл бұрын
Explanatory functions and variables are so helpful. For not so long ago, I came across a function in the codebase at work which was over 100 lines. It did so many things in such weird ways. That usually happens when you have plenty of devs working in their own styles, and everyone is "afraid" to refactor what someone else wrote, so they just end up patching things on top of each other, ultimately creating a big mess.
@nmoschen
@nmoschen 3 жыл бұрын
As always, I couldn't agree more with you. Readability is key. Keep up the good work! 👏
@victornikliaiev466
@victornikliaiev466 3 жыл бұрын
Thank you Kyle! it's a great practice!
@mohamadabdelrida2866
@mohamadabdelrida2866 3 жыл бұрын
This video definitely earned my sub. I will try incorporating this tip in my code 👍
@Mr.Nichan
@Mr.Nichan Жыл бұрын
What's nice about this explanation is that it explicitly addresses the counterarguments.
@djpeterson7479
@djpeterson7479 3 жыл бұрын
This is something I've been doing lately and have been very glad I do it. Other developers that I work with don't do this as often and it can take quite some time to add/fix features when you have to dig through a 100-line function that is branching through direct DB calls. If I know the problem is with contact updates, then having an updateContact() function makes it eons easier for me to figure out where I need to start my search. I highly recommend this programming style not just to help new developers, but for also speeding up code maintenance for future devs of any level to understand what your code is doing. I've also had this help me reason through design strategies of code as well. You tend to write less code that doesn't do anything or does weird stuff when everything is a micro function.
@OwenRalph
@OwenRalph 3 жыл бұрын
Totally agreed with your argument here about making the code as immediately readable as possible. It's also why I completely disagree with you about removing 'else' in favour of scattering 'return' all over the place.
@y2an
@y2an 9 ай бұрын
Very much a fan of this style, it expresses the spec (if any!) directly and is easy to test and modify. If there is any optimisation which could be performed by collapsing the functions, it should be done by the compiler.
@mohamedaljamil6334
@mohamedaljamil6334 3 жыл бұрын
I have been working on a REST node integration, the previous dev wrote 7 endpoints with around 500 lines of code. with nested IFs. took ages to understand what was going on. After refactoring each endpoint had clear 10 - 20 lines of code. with models and adapters that serve a single purpose. We should teach this to all junior devs. good job Kyle
@vinkalmann
@vinkalmann 3 жыл бұрын
This is slick, well done!
@scriptedpixelsltd
@scriptedpixelsltd 3 жыл бұрын
100% agree with this; have been doing this for a short while & it felt odd at first but going back to the feature I worked on last year at my new job was very very easy to see what I was thinking & what is happening with the app
@love-hammer
@love-hammer 3 жыл бұрын
This is so important in real world scenarios. I recently found a bug in some code that had barely been touched in 2 years where essentially the createContact function is 200-300 lines long with no comments and if the issue wasn't one line in 300 it probably would have been caught immediately by team members familiar with the API.
@roke77
@roke77 3 жыл бұрын
One of the best quotes I remember from the Clean Code book is one that says that programming is a social activity. The more understandable you make your code, the more efficient your collaborative work will be.
@Hangoutapp
@Hangoutapp 3 жыл бұрын
That's what I'm talking about?
@jacobm1190
@jacobm1190 3 жыл бұрын
You also might just be collaborating with your future self
@skaruts
@skaruts 3 жыл бұрын
I was skeptical at first, as I usually am with people giving advice/opinion on coding practices, but when I saw that new version of the code I was impressed. The thing is, I know next to nothing about whatever that code is for, but you still made it pretty straightforward for me to have a clear idea of what it does.
@pcdispatch
@pcdispatch 3 жыл бұрын
Often it is not so important what some piece of code does. The thing which is important is WHY. You need comments to explain about the reasons for some code or functions calls. People who say they don't write comments are probably only working on simple software projects.
@jamshediqbal7936
@jamshediqbal7936 3 жыл бұрын
Kyle, that's great and that's exactly how we should do. Because it isn't about writing code for yourself but also for other devs who should understand what you wrote at first glance. Moreover, some people may think, it may create big and extra code, making js file quite large to load slower in your Network tab. But, believe me, it isn't the case these days if you are using some kinda library like React or development bundle like webpack, which makes your final js file shrunk, minified and smart enough to load faster at the end.. :)
@arjix8738
@arjix8738 3 жыл бұрын
Well, in terms of filesize it hardly has a difference. But in terms of text size it does, there are cases were code like this looks like it is obfuscated. There is no point in making a function to do a mathematical addition, and if you do you are making it harder to read. Splitting the code to functions is nice, but when overdone its not.
@kjyhh
@kjyhh 3 жыл бұрын
Great! I learned a lot. Thanks a ton!
@vivekkaushik9508
@vivekkaushik9508 3 жыл бұрын
The purpose of function chaining is not just to write "clean" code but rather to "reuse" repeatable code. Suppose you were going to use getContact and updateContact often throughout your application in various modules. Then you could simply export those functions from a single file and use them as imports in another file. Similarly, if some code is getting lengthier and complex, it's better to break it down into most basic units(functions) and then chain(compose) them together to provide a clean and understandable layout to anyone who dares go down that rabbit hole. The purpose isn't to write "cool" code but to provide a solution without creating another problem i.e, understanding it.
@trappedcat3615
@trappedcat3615 Ай бұрын
I agree, but it does not make sense to break it down if the functions are only needed once.
@powderriverfarrier
@powderriverfarrier 3 жыл бұрын
Raising the point of making it easier to write unit tests is excellent and right on target. Going point Kyle.
@jeddals3613
@jeddals3613 3 жыл бұрын
Hey Kyle, Love the vids. A video idea, instead of dev stuff, could we get a setup tour. Including your monitors, peripherals, pc specs, etc. I would really love to see this 😊.
@elierh442
@elierh442 3 жыл бұрын
I totally agree with you. I started to wring code like the first example, later I realized I was able to better understand my own code if I followed the single responsibility principle.
@savannahlin8063
@savannahlin8063 3 жыл бұрын
Straightforward is important. I agree with you.
@edycole5543
@edycole5543 3 жыл бұрын
Thank kyle. Simple. Easy to read, easy to code, easy to maintain👌
@bradleynall2698
@bradleynall2698 3 жыл бұрын
Love this practice man.
@S0p0r10
@S0p0r10 3 жыл бұрын
It is important to stay at the same level of abstraction in each function. Nice explanation :)
@jamescanady8156
@jamescanady8156 3 жыл бұрын
What I like to do is as I'm writing a function, I'll actually use a reference to a function that might not exists yet. In your example. I know I need to get a contact, so I would create the reference as you have there, and then fill in the gaps by defining the function.
@francispineda971
@francispineda971 3 жыл бұрын
aka “writing the code you wish you had”
@nowyouknow2249
@nowyouknow2249 3 жыл бұрын
Yeah thats true n cool. I do that too. Everything just flows like a story book.
@srinathsathyanath7435
@srinathsathyanath7435 3 жыл бұрын
Your videos just get better 👍👍👍
@LogicEu
@LogicEu 3 жыл бұрын
In JavaScript we don't always care about performance, but for optimizing, is good to minimize function calls as much as possible because they add indirection and the CPU can't predict what's gonna happen. Nevertheless, I often use this approach when developing so the code is more readable and simpler, and optimize it at the end for shipping.
@kastermester
@kastermester 3 жыл бұрын
While I understand that you are agreeing with the point of the video - even the concerns raised here should not be a worry to you. Modern JavaScript engines are extremely sophisticated and I would be extremely surprised if even a single one of them would not optimize this by inlining the helper functions (assuming the code is being deemed important enough to spend time optimizing it). If “it ought to work” is not enough, then I would advocate spending some time setting up a proper build pipeline that can inline the code during build. Unless you absolutely know that it makes a tangible difference - you should never be worried about reorganizing code for readability due to performance concerns like this, it is a very dangerous road to go down.
@sonamuhialdeen7866
@sonamuhialdeen7866 3 жыл бұрын
Awesome information
@darrengrant8598
@darrengrant8598 3 жыл бұрын
Great leading question for writers: Can I glance at this and understand it? When applicable: Can others glance at this and understand it? Reflection for readers of other potentially complicated code: What are the relationships and key concepts here? (Can I work out the meaning from the structure as well as the words?)
@nothingisreal6345
@nothingisreal6345 3 жыл бұрын
This is the single most important technique to write robust code! Write a function that adresses a single concern in an atomic way. CreateStuff, ReadStuff, UpdateStuff, DeleteStuff. And try to follow well known patterns, here CRUD = Create, Read, Update, Delete. Once you have created these building blocks combine those into macro code that only glues together atomic operations in a very simple manner. Everything that can be executed by itself in a meaningful way is a function! In more formal languages like C#, Java, C++ the next step is to define interfaces and then implement them. The point of easier testing is also VERY important. Another rule of thumb is: the human brain can only process 7 +- 3 items. If you add more items you tend to forget the first item. So about 10-15 lines of code per function make it very easy for a reader to put the whole code into his awareness at once. You can have lines more in a code block for opening and closing brackets etc. Even more important is to avoid deeply nesting code. Studies have proven that if more as 7 levels of nesting occur, without aggregating levels into separate functions, the error rate will reach 100% even for the smartest developers.
@Wong-Jack-Man
@Wong-Jack-Man 3 жыл бұрын
I agree. Our brains process and store information better if its compartmentalized and using functions makes it easier. Doesn’t matter if the function isn’t necessarily reused.
@neoplumes
@neoplumes 3 жыл бұрын
I do set a 31-line limit for myself, but because that's how many lines fit on my screen. I've found that I can only fit one screen's worth of code in my head at a time. Either way, I wish more people used self-documenting code like you describe.
@bagaskara1567
@bagaskara1567 3 жыл бұрын
Nice tipss 👍🙏
@ferdinandocoluccelli9574
@ferdinandocoluccelli9574 3 жыл бұрын
I totally agree with you Kyle!
@theManuelOsorio_
@theManuelOsorio_ 3 жыл бұрын
This is something I've been slowly starting to do with my nodejs api. I've had my routes split to 2 files originally. I started refactoring my code by having smaller files that contain there on crud functions. Now I've been refactoring my functions and making smaller functions for repeated code. The next step will be make small function for the remaining complex code blocks.
@nikensss
@nikensss 3 жыл бұрын
I couldn't agree more with you. I think it's in `Clean Code` where Robert Martin explains that super small functions with very descriptive names are absolutely worth it. Even for cases like: if (variable.field !== CONSTANT) moving it to if (variable.meetsCriteria()) is so much cleaner. Much less cognitive load.
@jjfattz
@jjfattz 3 жыл бұрын
Great tips
@teytag8844
@teytag8844 3 жыл бұрын
One consideration for a counter point. Its not uncommon for multiple features to have a similar decision tree (if contact == null ....). If we apply the 'write smaller functions' strategy, you'll quickly end up with a few logic flows which define `getContact` locally. Further, its likely that X number of these helper functions would have the same logic, but in a few instances the logic is slightly different. For someone coming into a project with no knowledge, it MIGHT be confusing to see `getContact` defined as a new functoin in a number of different files. A dev might then be tempted to abstract all of the `getContacts` into a single export so it can be re-used, but remember how some of the local versoins have edge cases? If you push through with the abstraction, you'll end up with a single `getContacts` that handles all cases, which would in turn make it less readable (e.g., why is this exception being made). My point is; I fully agree with your proposed strategy. It makes sense. The catch is that if you're not fully aware of how to use the pattern, it opens up the door for unnecessary refactors, or for the need for someone to keep track of which helper utility does what in what file.
@multiwebinc
@multiwebinc 3 жыл бұрын
You just inspired me to refactor this 237 line function I've been working on down to 29 lines.
@shuku10
@shuku10 3 жыл бұрын
You explained it so easy, good job there. In your videos, you use ES5 functions intead of ES6, any particular reason?
@blackcateve
@blackcateve 3 жыл бұрын
I think it depends on how complex your code is, and how often you need to modify your code. In general, I really dislike and generally avoid small blocks in big systems or during Agile development. Maintaining such codes is really not ideal even if it is understandable, imagine jumping back-and-forth files and functions multiple times to fully understand the whole process. Even if it understandable, it is often insufficient. Just like updateContact function, you need to go into the function anyway to know what fields you are updating or updating to where. I also notice people who write in such a way often write their codes in a very sub-optimal way, it is sometimes so complicated that it would be easier re-writing the whole thing However, such approach is definitely ideal for frontend coding since it is usually less complicated
@luczztem
@luczztem Жыл бұрын
my code looks exactly like the above example, so confusing... I will immediately start applying your tips. thanks so much
@dallinpoulson2176
@dallinpoulson2176 3 жыл бұрын
This is how my current programming professor has us write code and I think it’s great
@hamadaparis3556
@hamadaparis3556 2 жыл бұрын
It's amazing technique thank you so much
@pascalrenner4320
@pascalrenner4320 3 жыл бұрын
That's a clean coding style. A rule of thumb can be: All lines that belong logically together need to be put into on function. Do you handle different logics in a function - seperate the code into different functions. Do you handle different topics (e.g. user input, validation, ...) - seperate code into functions in different classes.
@luczztem
@luczztem Жыл бұрын
this is an incredible video I love you so much
@olafbaeyens8955
@olafbaeyens8955 6 ай бұрын
Nice advice. The way U develop code is in such a way that one method does one thing and every method can be put on your screen without need of scrolling. I do comment my methods for an obvious reason. If you cannot describe the method you create in a user friendly way then you code is not designed well. It also is a double check. When your method comments is out of sync with the code then someone did a rush job and it forces you to look at the code to check if it is correct. Update the comments section so you know that someone peer reviewed it. Commenting you code can also be done by writing the user friendly logging in such a way that the logging describes how your method works. The logging code can then take over the comments parts. And at the same time the log file can contain how it got to a point where it threw an exception. The more user friendly the logout put is the more support can resolve issues and the less they annoy you with fires in production.
@andymounthood
@andymounthood Жыл бұрын
I've been trying this approach (and I like it) but it quickly became spaghetti code of another sort: a huge, unruly list of functions. Maybe the solution to that would be nested functions? If a function is only used once, maybe I should nest it inside the function that calls it? Then I can collapse the larger function unless I need to look inside it. What do you think?
@jindrichsirucek
@jindrichsirucek Жыл бұрын
exactly my thinking when watching this
@kwangsamyew8469
@kwangsamyew8469 3 жыл бұрын
great video on a topic not many coders talk about. could you do a video on how passing in callback functions as parameter to your defined function is a good pattern
@piotrswobodzinski3549
@piotrswobodzinski3549 3 жыл бұрын
good idea mate
@burnaDLX
@burnaDLX 3 жыл бұрын
You misspelled Promise
@joseluisperez5137
@joseluisperez5137 2 жыл бұрын
Im gonna try it!
@harag9
@harag9 3 жыл бұрын
100% agree with you. KISS (Keep It Stupidly Simple) - I also don't put comments in my code, because you should be able to read the code and know what it does, especially with a good naming convention. "updateContract" vs "updCon". I use a plugin with VSCode called "CodeMetrics" which I use as a guide line, if I see the number getting too high, then I break it down.
@isen1
@isen1 2 жыл бұрын
uncle bob would be proud! great example of clean / readable code and SRP
@JethroSas
@JethroSas 3 жыл бұрын
great! thanks for this! :)
@abhijiths148
@abhijiths148 3 жыл бұрын
This is one of the basics that we should study in college once you know the language concepts.
@IsThisLossE
@IsThisLossE 3 жыл бұрын
i'm glad my university has a class about functional programming. it's just an elective, but i think i've learned more from my that class than any other about 'proper code etiquette.' i think if i was introduced to it at the beginning of my degree and forced to use it a bunch in the middle that i would understand much, much more than i do now. oh well!
@zander6100
@zander6100 3 жыл бұрын
It's kind of the S in the SOLID programming principle applied deeper down
@ChellADurAiR1990
@ChellADurAiR1990 3 жыл бұрын
hey Thanks, I also like to write more small functions, but my team lead who do code review say that's not good practice, why we have more function calls(main function call other function that function call one more function and the next one call one more, so 4 stack levels), what's your thoughts on this?
@anothermouth7077
@anothermouth7077 3 жыл бұрын
Same, also I do not like calling one helper function from another helper function but my lead puts a comment on it every time while reviewing
@alxjones
@alxjones 3 жыл бұрын
You need to use discretion, it's easy to take this principle so far that you have 4+ stack level for a simple task. Remember that the main point is that each function does 1 thing, so if you have to break up a function twice, your function probably did more than one thing. The biggest exception are the entry points (main, http endpoints, etc.), which necessarily perform large complex tasks. That said, a stack depth of 4 is not really an issue as long as the function splitting is meaningful. In fact, it probably does more good than harm since your stack trace help isolate bugs, and running a debugger on code split out into functions "deeply" is a really easy and pleasant experience. The only downside is the slight performance overhead of calling functions, which is 99.99% of the time not worth bugging out about.
@ChellADurAiR1990
@ChellADurAiR1990 3 жыл бұрын
@@alxjones Thanks Alex, it’s useful 😀
@anthonyhenderson3189
@anthonyhenderson3189 3 жыл бұрын
I'm at work listening, I can't wait to try this with my portfolio.
@lucasguima
@lucasguima 3 жыл бұрын
great video, I prefer that approach too! one question now: how to test those functions not exported?
@lu_ck
@lu_ck 3 жыл бұрын
i feel like the compiler doesn't like that, is it efficient at all? looks fun to use!
@mrwerevamp
@mrwerevamp 3 жыл бұрын
Hey lol that is what I did with all my stripe functions! I put all of them in a /stripe directory.
@ddanielsandberg
@ddanielsandberg 3 жыл бұрын
Levels of Abstractions. Move technical details down, do it well enough and your high-level policy reads like a requirement/use-case that even your project manager can understand. The real problem with large functions is HOW they became that way. There are way too many of us programmers that thinks that programming means sitting alone in a corner, with our headphones on listening to "Synthwave programmer focus mixes". The argument is often that "I need to focus, large functions are easier to make, everything in one place, I can see everything I'm working on, etc". We tend to end up in some kind of strange trance where we basically turn our brains into interpreters and a stack. We have the entire flow, the state of every variable at the 5th if-else level of nesting... and then a colleague says "hey, how does this other thing work again? Wanna go to lunch?". And poff, gone, stackoverflow and it takes 20 minutes to get back to where we were. The most common response to this is to isolate oneself even more, headphones, "keep out signs", working from home with Slack/Teams/Phone turned off. Of course, when we get it to work we feel like superheroes. "I'm awesome, I pulled it off. Did you see the complexity of that thing?" And then we have the problem that the functions become hard to understand, it's easier to make mistakes, people becomes afraid of making changes and at most we add another if-statement at the beginning or end of the function instead of changing the rest of the function. There is this old joke: - "How did this function become 2000 lines long?" - "One if-statement at a time." - "Why?" - "Fear." Here is the point. The problem is not that we are getting disrupted, it's that we are working wrong and way too hard instead of smarter. It's not about how fast you write it the first time, it's how fast/safely you can make the 100th change and how much time everyone on the team (including you) need to spend reading the code over and over again to get their work done. In essence this well known meme heeris.id.au/trinkets/ProgrammerInterrupted.png is an anti-pattern. You can't handle a reasonable amount of disruptions? It's not their fault!
@lukas7338
@lukas7338 3 ай бұрын
since this adds more code, how do you structure your project and classes with this much helper code?
@Brian-og6kk
@Brian-og6kk 3 жыл бұрын
I have watched so many of your videos. They are some of the best out here for coding help. the way you break it down so easily. I'm currently 39 (the big 4-0 is coming in a few days, sheesh) and I was born into an underprivileged family. I was in and out of the foster system growing up. I ended up going into the workforce as soon as I could at 16, and have busted my but for scraps my whole life. I recently got the opportunity to stay at home and learn coding, and it has been a huge success. Then I realized how life changing this is, and to learn it all you need is a very basic cheap computer and internet access. Now I know what my purpose in life is, it is to make this technology accessible to as many underprivileged people as I possibly can. Today a couple friends I met in school and I are getting together to lay down the groundwork for something that hopefully helps change the course of many underprivileged families. I feel like I have finally found my purpose in life, and I can't thank you enough for the videos you have posted here. I don't think you even realize the importance of all of your work. You are amazing.
@AbhinavKulshreshtha
@AbhinavKulshreshtha 3 жыл бұрын
Nice explaining, For anyone who thinks this will add overhead, it will. But worry not, Browser jit should take care of it but make sure jit in integrated in node. There are some optimising aot too which should reduce memory overhead. But being an old school programmer, I do worry that these days, programmers tends to take memory and resources for granted.
@Erlisch1337
@Erlisch1337 3 жыл бұрын
Yeah, if you are doing low level C/C++ you might want to avoid these extra function calls (tho the compiler will probably inline them anyway....but you can't be sure). But for JS it wont matter much.
@AbhinavKulshreshtha
@AbhinavKulshreshtha 3 жыл бұрын
@@Erlisch1337 I think you got it in reverse. In c/cpp, or any compiled language, compiler can inline these, therefore you dont need to avoid it. Js is interpreted, JIT will only store compiled body of functions, function calling overhead will still be there. Yes it's not 1980s so you don't need to worry about these micro optimization. Readability is important. But you should also not forget these concepts.
@montebont
@montebont 5 ай бұрын
In general I'm not a fan of your approach but this makes perfect sense. Thnx
@knowledgegeeks3901
@knowledgegeeks3901 3 жыл бұрын
Great video
@zigaudrey
@zigaudrey 3 жыл бұрын
I learn a piece of Javascript code that switch to the next image each time we clicked on it and I don't get what is the point of "return". Without it, the script is still working. When "return" is necessary? The syntax is so confusing. I am used to Python.
@okdoomer620
@okdoomer620 3 жыл бұрын
There is also the possibility to nest functions if you only ever use functions from within another function. That gives you cleaner namespaces and otherwise your file can get messy if you have many functions that you split up into even more functions
@Bozoki8989
@Bozoki8989 3 жыл бұрын
Hi, you have great videos! Any chance you make one on logging in NodeJS? Like the different libraries, best practices, etc.. Thanks!
@ABMedia83
@ABMedia83 8 ай бұрын
Yep, I do this all time when writing C#. Try writing a WPF application without simplifying some WPF plumbing. Good luck!
@hamidsamimi3788
@hamidsamimi3788 3 жыл бұрын
Great video. But, that's why we create things called services. One way would be to create a new service for every entity you have in your data model. Another way would be to take advantage of OOP and create a BaseService class that does the basic CRUD actions 90% of entities of your data models need and extend the BaseClass and passing the endpoints name using the constructor and using them where you need them. This way you abide by DRY and KISS. I know many of you might be against creating objects but this makes code maintenance way easier and by extending a base service that provides 90% of your functionality, the other 10% of custom logic can either be overridden or added very easily.
@ffedchik
@ffedchik 3 жыл бұрын
Very, very good!
@palitroche0518
@palitroche0518 3 жыл бұрын
I just noticed that he speed up his video to avoid us losing time. Nice!
@Crackhog
@Crackhog 3 жыл бұрын
Is this also recommended for the front-end code? Since having more functions increases file size thus effectively increasing load times
@daleryanaldover6545
@daleryanaldover6545 3 жыл бұрын
well, having more functions is just a small price to pay in exchange to make code easy to read, maintain and scale I wrote a chrome extension for twitter that had many small functions in it. Left it for over a month, after coming back to work at it again those small functions really did help me get my bearings back and understand what I wrote a month ago. Some of the functions are also reusable which makes adding additional feature really easy.
@mr_superhaggis
@mr_superhaggis 3 жыл бұрын
Appreciate and agree with the need to break things down into small reusable parts. My only comment is your use of a global variable to represent the API instance. Would it not be more in keeping with your design to have a function that produces a configured API instance instead of assuming it exists in scope within your functions and that is ready to be used?
@mericet39
@mericet39 3 жыл бұрын
This is right, and it's the S in SOLID: Single-responsibility. A function should do one thing - what it says on the tin, and no more. It should not have unexpected side-effects. Using if-blocks to check if something is null and doing something based on that check is not ideal. I'm more of a Java guy than Javascript, so I'd use Optional. But I think you can do optional chaining ?. to reduce the need of these if-blocks.
@otesunki
@otesunki 3 жыл бұрын
"Simple is better than complex" "Readability counts" "If an implementation is easy to explain, it may be a good idea"
@Hangoutapp
@Hangoutapp 3 жыл бұрын
Hey Kyle like KZbin comments. How do you make an commen public. Meaning. Whenever you refresh the page you still gets the user information. On html or JavaScript Edit: Please answer.
Watch This If You Don’t Understand Type Coercion
8:19
Web Dev Simplified
Рет қаралды 128 М.
Why I Don’t Use Arrow Functions With const/let
6:48
Web Dev Simplified
Рет қаралды 183 М.
Como ela fez isso? 😲
00:12
Los Wagners
Рет қаралды 25 МЛН
Joven bailarín noquea a ladrón de un golpe #nmas #shorts
00:17
Osman Kalyoncu Sonu Üzücü Saddest Videos Dream Engine 118 #shorts
00:30
Clean Code Is Killing Your Projects
9:20
Web Dev Simplified
Рет қаралды 141 М.
Junior Vs Senior Code - How To Write Better Code
22:13
Web Dev Simplified
Рет қаралды 1,1 МЛН
Learn useMemo In 10 Minutes
10:42
Web Dev Simplified
Рет қаралды 461 М.
Before Your Next Interview Watch This
14:18
Web Dev Simplified
Рет қаралды 143 М.
Learn Dynamic Module Imports In 11 Minutes
11:37
Web Dev Simplified
Рет қаралды 139 М.
5+ Must Know HTML Tags That Almost Nobody Knows
15:33
Web Dev Simplified
Рет қаралды 612 М.
Learn JavaScript Array Reduce In 10 Minutes
10:22
Web Dev Simplified
Рет қаралды 195 М.
Every JavaScript Developer Has Made This Mistake With Functions
7:17
Web Dev Simplified
Рет қаралды 104 М.
8 Python Coding Tips - From The Google Python Style Guide
17:12
ArjanCodes
Рет қаралды 153 М.
Como ela fez isso? 😲
00:12
Los Wagners
Рет қаралды 25 МЛН