Why I Never Write Long Functions

Поділитися
Вставка
  • Опубліковано 8 вер 2024

КОМЕНТАРІ • 439

  • @Stoney_Eagle
    @Stoney_Eagle 3 роки тому +364

    This is how you write code without comments. It's self explanatory.

    • @joe-un1ky
      @joe-un1ky 3 роки тому +20

      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 роки тому +8

      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 роки тому +1

      @@wasd3108 yes exactly

    • @markmanning2921
      @markmanning2921 3 роки тому +5

      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 роки тому +1

      @@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 роки тому +55

    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 5 місяців тому

      Do one-liners like this really need testing, though. I guess it depends, but here it just means more unnecessary tests.

  • @KaroCodes
    @KaroCodes 3 роки тому +260

    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 роки тому +32

      I couldn't agree more.

    • @pastagaz4241
      @pastagaz4241 3 роки тому +3

      Agree. If your code is readable/understandable, comments are useless. Most of the time, lot of comments == unreadable code

    • @nowyouknow2249
      @nowyouknow2249 3 роки тому +2

      Every function should have a doc string description of what it does atleast according to pep8 in python

    • @berylliosis5250
      @berylliosis5250 3 роки тому +1

      @@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 роки тому +1

      That's a pretty dumb idea, in my opinion.

  • @travcurt
    @travcurt 3 роки тому +42

    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 роки тому +8

      @@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 роки тому +1

      @@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.

    • @WatchesTrainsAndRockets
      @WatchesTrainsAndRockets Рік тому

      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 роки тому +51

    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 роки тому +4

      I really like this way of looking at it

    • @alister_
      @alister_ 3 роки тому +11

      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.

  • @tudor414
    @tudor414 3 роки тому +50

    It's exactly what I always try to explain to the team. "Write the code to be like a story."

    • @Blast-Forward
      @Blast-Forward 11 місяців тому

      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 11 місяців тому

      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.

  • @code_lift
    @code_lift 3 роки тому +53

    wow, nice. I'll give this a shot. Also, great job at showing more personality. You seem more like yourself.

    • @WebDevSimplified
      @WebDevSimplified  3 роки тому +17

      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

  • @Gorgamela
    @Gorgamela 3 роки тому +4

    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.

  • @ayushdedhia25
    @ayushdedhia25 3 роки тому +64

    Hate writing comments while coding? Then write the code as Kyle does...! ❤️ Which makes your code self explanatory 🔥😎

    • @carlarmbruster
      @carlarmbruster 3 роки тому +7

      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.

  • @berylliosis5250
    @berylliosis5250 3 роки тому +6

    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 Рік тому

      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 11 місяців тому +1

      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.

  • @jimmorrison2657
    @jimmorrison2657 3 роки тому +7

    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.

  • @thecodecatalyst
    @thecodecatalyst 3 роки тому +40

    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 роки тому +2

      "single responsability"

    • @dcmbassi
      @dcmbassi 3 роки тому

      Bow before the God Object!!!

    • @karanparmar4318
      @karanparmar4318 3 роки тому +7

      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 роки тому +2

      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)

  • @pensums
    @pensums 3 роки тому +5

    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 Рік тому

      @@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

  • @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.

  • @briandev8
    @briandev8 3 роки тому +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.

  • @Mr.Nichan
    @Mr.Nichan Рік тому

    What's nice about this explanation is that it explicitly addresses the counterarguments.

  • @roke77
    @roke77 3 роки тому +9

    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 роки тому +4

      You also might just be collaborating with your future self

  • @nemesioansorin
    @nemesioansorin Рік тому +1

    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.

  • @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.

  • @vivekkaushik9508
    @vivekkaushik9508 3 роки тому +4

    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 5 місяців тому

      I agree, but it does not make sense to break it down if the functions are only needed once.

  • @JimRooney
    @JimRooney 3 роки тому +1

    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

  • @jamescanady8156
    @jamescanady8156 3 роки тому +9

    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 роки тому +2

      aka “writing the code you wish you had”

    • @nowyouknow2249
      @nowyouknow2249 3 роки тому +3

      Yeah thats true n cool. I do that too.
      Everything just flows like a story book.

  • @love-hammer
    @love-hammer 3 роки тому +1

    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.

  • @stephan5512
    @stephan5512 3 роки тому +2

    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

  • @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.

  • @LogicEu
    @LogicEu 3 роки тому +4

    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 роки тому +1

      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.

  • @yamogebrewold8620
    @yamogebrewold8620 3 роки тому +2

    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.

  • @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?)

  • @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

  • @neoplumes
    @neoplumes 3 роки тому +2

    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.

  • @blackcateve
    @blackcateve 3 роки тому +2

    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

  • @olafbaeyens8955
    @olafbaeyens8955 10 місяців тому

    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.

  • @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.

  • @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!

  • @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.

  • @luczztem
    @luczztem Рік тому

    my code looks exactly like the above example, so confusing... I will immediately start applying your tips. thanks so much

  • @theManuelOsorio_
    @theManuelOsorio_ 3 роки тому +1

    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.

  • @gianancheta2955
    @gianancheta2955 3 роки тому

    I find your channel one of the most helpful resources to learn writing code well!

  • @filipe_paixao
    @filipe_paixao 3 роки тому +1

    You are one of the few guys I can say I love with confidence.
    thank you for this bro

  • @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.

  • @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.

  • @y2an
    @y2an Рік тому

    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.

  • @kirillvoloshin2065
    @kirillvoloshin2065 3 роки тому +1

    very clear explanation, thank you! I guess this approach is ideal for our small projects with the possibility of future support.

  • @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 роки тому +1

    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 роки тому +1

      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.

  • @otesunki
    @otesunki 3 роки тому +1

    "Simple is better than complex"
    "Readability counts"
    "If an implementation is easy to explain, it may be a good idea"

  • @dallinpoulson2176
    @dallinpoulson2176 3 роки тому +2

    This is how my current programming professor has us write code and I think it’s great

  • @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.

  • @pastorfred2543
    @pastorfred2543 3 роки тому +2

    Great explanation with plain example. Thanks Sir Kyle

  • @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! 😃

  • @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.

  • @abhijiths148
    @abhijiths148 3 роки тому +19

    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

  • @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.

  • @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.

  • @B00Mnation
    @B00Mnation 3 роки тому

    The smallest of nitpicks: I love writing functions this way too, but if you want to make them even more readable, order their definitions according to the order of their usages. This way, when you’re reading through the higher-level function and come across the first usage like “getContact(...)”, you can easily find its definition right below. Then, as you come across other function calls, you know they will be defined chronologically. Less jumping around your file to find definitions = better

    • @matejlaskomulej
      @matejlaskomulej 3 роки тому

      Agree on the order, but one usually wouldn't scroll to function definition, would one? Not with the Ctrl+click and keyboard shortcuts available.

  • @isen1
    @isen1 3 роки тому

    uncle bob would be proud! great example of clean / readable code and SRP

  • @andymounthood
    @andymounthood Рік тому +3

    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?

  • @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.

  • @ABMedia83
    @ABMedia83 Рік тому

    Yep, I do this all time when writing C#. Try writing a WPF application without simplifying some WPF plumbing. Good luck!

  • @Erlisch1337
    @Erlisch1337 3 роки тому +1

    Id say it depends on what youre doing - if youre using a language like JS then the extra function calls probably wont matter and its probably better to write this more readable code. But if you are writing low level C/C++ code then you probably want less function calls and want to avoid this.

    • @shexec32
      @shexec32 3 роки тому

      In C/C++ you should be using the inline keyword to eliminate the [supposed] impact of a function call.
      Or you turn on your compiler's aggressive optimisation flag (-O2 or -finline-functions in GCC, /O3 for MSVC), where it treats every function as if it was tagged "inline".

  • @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.

  • @powderriverfarrier
    @powderriverfarrier 3 роки тому

    Raising the point of making it easier to write unit tests is excellent and right on target. Going point Kyle.

  • @multiwebinc
    @multiwebinc 3 роки тому

    You just inspired me to refactor this 237 line function I've been working on down to 29 lines.

  • @oldclient
    @oldclient 3 роки тому +6

    Well, it requires some good experience to know when certain coding patterns should be used or how to fragment the code into some reusable logic blocks.
    Otherwise it can turn into a total verbosity mess.

    • @mupert_rerdok
      @mupert_rerdok 3 роки тому

      You won't have experience until you start doing it ;)

  • @mohamadabdelrida2866
    @mohamadabdelrida2866 3 роки тому

    This video definitely earned my sub. I will try incorporating this tip in my code 👍

  • @LawZist
    @LawZist 3 роки тому

    Every developer on all levels should see this video!

  • @arraymac227
    @arraymac227 3 роки тому

    The beauty here is that inlining all the functions that are suggested by the initial comments, that inlining becomes unnecessary, and also counterproductive.

  • @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

  • @oleg_deezus
    @oleg_deezus 3 роки тому +2

    There's one extra reason to write code like this: you don't have to jump to your code from stack trace in the error message to figure out what went wrong.

  • @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

  • @TheShadowFlareGaming
    @TheShadowFlareGaming 3 роки тому

    I mean, this example is completely different than before, not only are these not one time methods as I'd be genuinely surprised if this is the only time you create a contact, but you're also applying it completely differently.
    Instead a more accurate representation would be if you took the entire if statement and copied into a single method and renamed it to something like handleLink or some crp like that.
    That said, points are there and its good tips for reusability and self documenting code, just doesn't solve the problem of where people were complaining.

  • @jasongoossens
    @jasongoossens 3 роки тому

    Last week I had to refactor some code I wrote that was similar to yours (not called anywhere else, no real reason to split it up except for readability, etc).
    I spent half a day refactoring 2 AJAX calls into one, just cause the code did too much... Small functions is the way to go. Just looking at the code you know what it's doing and know where to look for specific details.... (although, in the real world it isn't always easy to do it this way, and while writing new code, you sometimes just want to get it working and only refactor after realizing it works, but is hard to understand - edit: typed this halfway through the video... Looks like you mentioned it :-P)

  • @montebont
    @montebont 9 місяців тому

    In general I'm not a fan of your approach but this makes perfect sense. Thnx

  • @krowvin
    @krowvin 3 роки тому

    To add to this, assuming someone hasn't already said it, this will save you time down the road refactoring. The functions he made could be used in later features.
    Then you could reuse the createContact/updateContact

  • @AbhinavKulshreshtha
    @AbhinavKulshreshtha 3 роки тому +1

    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.

  • @Dawamesk420
    @Dawamesk420 3 роки тому

    Had some discussion around this topic with a professor who insisted on comments in code. While sometimes relevant, often enough comments are redundant when writing self-documenting code. Basically, can you give a name to some few lines of code? In that case name an actual function like that. Usually in the form of DoStuffWithThing(thing)

  • @TFDusk
    @TFDusk 3 роки тому

    Highly recommend if you want to upgrade your own skillset to read clean code. People as devs forget that when you write code on a team, you are not writing it for yourself. You're team needs to understand what it is that you write. Comments IMO are a failure to be able to explain what is happening with the code, having simple and short functions with descriptive names is the way to go. Not only is the code Kyle posted her much simpler to understand what is happening, the code is more deterministic, which allows it to be easier to test, its associative, meaning the example he shows her is all relatable code that reads much like a book, and it's small, meaning it is easy if I wanted to change around some of the logic to be able to extend or shrink the features that this offers.
    This is some of the stuff I strive to get better into as a junior developer at my job.

  • @patrickp.6947
    @patrickp.6947 3 роки тому

    The problem with this in my company is that, they create sub function with shared scope. It's terribly ugly and tricky. They do this to avoid the top down due to function split in the rootscope. The solution to this has been to create one file for each exported function which has some other drawbacks bit it's pretty much ok when the file system is well organized and function does not need each other in a loop.

  • @suche_cz
    @suche_cz 3 роки тому

    function should be :
    Small.
    Do one thing.
    Use descriptive names.
    Prefer fewer arguments.
    Have no side effects.
    Solve a problem on same level of abstraction. (a lot of nested blocks is sign that violates this rule)
    Don't use flag arguments. Split method into several independent methods that can be called from the client without the flag.
    source: Clean Code

  • @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 😊.

  • @savannahlin8063
    @savannahlin8063 3 роки тому

    Straightforward is important. I agree with you.

  • @S0p0r10
    @S0p0r10 3 роки тому

    It is important to stay at the same level of abstraction in each function. Nice explanation :)

  • @azfarazman7750
    @azfarazman7750 3 роки тому +2

    Thank god I'm not crazy. I'm being doing this for the past 5 years and I am walking in a garden every time.

  • @kwangsamyew8469
    @kwangsamyew8469 3 роки тому +2

    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

  • @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?

  • @mindblower113
    @mindblower113 10 місяців тому

    Eventually, I had found this solution when working with APIs heavily. It just came by itself.

  • @victornikliaiev466
    @victornikliaiev466 3 роки тому

    Thank you Kyle! it's a great practice!

  • @Evilanious
    @Evilanious 10 місяців тому

    It's readable in the sense you know what it accomplishes, but if you have to debug something you'll soon be wishing for a contiguous block of code.
    Personally I try to split chiefly in order to avoid duplication, though there's more ways to do that.

  • @edycole5543
    @edycole5543 3 роки тому

    Thank kyle. Simple. Easy to read, easy to code, easy to maintain👌

  • @doxed64
    @doxed64 Рік тому

    The only time I write comments is to define the inputs and outputs of a function, method, class. Or, as a abstraction/pseudo-code explanation of what's about to happen on the next few lines. It's never more than 3 lines, or else, it needs to be separated into more functions.
    A single scope (function, block) never has more than three levels of indentation(python) or {} in javascript.
    You're much more efficient writing "snippets" and gluing them together, than if you just write monoliths.
    I also never-nest and it makes my life much easier.

  • @tylovset
    @tylovset 3 роки тому +1

    I wonder how much this affects execution time/performance due to the increased number of function calls? Does javascript engines or typescript transpilers do any inlining optimizations? This could also affect translation speed due to larger source code? I don't know. Otherwise good advice which also experienced developers should take note of...

    • @gnautist
      @gnautist 3 роки тому +1

      Javascript engines very rarely do inlining, there is a million reasons that a javascript function might be modified by a side effect and so almost always it can't make the assumption that a functions behavior will be static, sometimes they will inline shorter nested functions. Certain bundlers like webpack will sometimes inline code, however it is far more likely not to for more functions. Basically the only thing you can really trust will be optimized is dead code elimination, and even that has strict limits.

  • @TheChodex
    @TheChodex 3 роки тому

    6:25 - you can go even a step further and just imagine that you have already written a function that does this so instead of writing comment:
    // 1. get user
    you can just image you already have a getUser function ex
    const user = getUser();
    And from there you can just pretend ok if I had user what will I do with him?
    const result = doSomethingWithUser(user)
    and then once you have these steps done (just like in your comments) you then implement these functions (you can apply the same process when implementing those smaller functions until you get small units or "leaf nodes" that you can then implement using TDD (since tests for them are often small and easy))
    This is the way of writing code "one line at a time" that minimizes the chance for bugs, since connectors to the logic are readable, and the actual logic is small and written with TDD (minimal chance for error)

  • @theoboldalex
    @theoboldalex 3 роки тому

    This video pretty much sums up the first few chapters of Uncle Bob's Clean Code.

  • @revenity7543
    @revenity7543 10 місяців тому

    You need to keep a lot of things in your mind when you debug that code.
    Without smaller functions it is really straightforward what will eventually happen.
    You should split functions when they are way too big like 100 lines or so.

  • @ferdinandocoluccelli9574
    @ferdinandocoluccelli9574 3 роки тому

    I totally agree with you Kyle!

  • @SrIgort
    @SrIgort 3 роки тому

    I mean, you could also use comments... But I agree with you usage of small functions in this case, it makes sense, is potentially reusable and independent, but in the case of the other video the potential reusability was non-existent and dependent on the original function...

  • @fenix20075
    @fenix20075 3 роки тому

    The only thing I am concern about is public function and private function declare. Anyway this idea works good.

  • @claudemartin5907
    @claudemartin5907 3 роки тому +2

    Instead of an explanation that is almost 10 minutes long just tell them to write the unit test code for the function. They will quickly understand why small units of code are much better.

  • @ChigozieOrunta
    @ChigozieOrunta 3 роки тому +1

    This is a perfect example of Clean Coding, just as Uncle Bob intended it to be!!!

  • @billy8461
    @billy8461 3 роки тому +1

    well, it all comes down to what you are building.
    Rn I am building a compiler for a small programming language and I have functions with
    more than 200 lines even tho I am trying to write them as small as possible so yea...