Don't Write Comments

Sdílet
Vložit
  • čas přidán 15. 01. 2023
  • Why you shouldn't write comments in your code (write documentation)
    Access to code examples, discord, song names and more at / codeaesthetic
    References:
    www.commitstrip.com/en/2016/0...

Komentáře • 2,8K

  • @arkadiusl620
    @arkadiusl620 Před rokem +10570

    There are two sides of this, either readable code with minimal comments or unreadable code with lots of comments. I think it's best to combine both approaches: unreadable code with minimal comments.

    • @orr4337
      @orr4337 Před rokem +660

      Finally someone gets me

    • @yourbigfan1777
      @yourbigfan1777 Před rokem +401

      Just a typical stackoverflow error fix code

    • @1Dr490n
      @1Dr490n Před rokem +68

      That's how I do it

    • @dimanarinull9122
      @dimanarinull9122 Před rokem

      as someone who works on reverse engineering code that was written as "unreadable code with lots of comments" I can gurantee you I don't care how much you comment when I need to figure out what this points to:
      some_asm_func(out_vec[n] + 6 * MY_OFFSET * BASE_SIZE, some_other_variables...);
      out_vec[n] += JUMP_SIZE * ANOTHER_MACRO_FOR_FUN;
      when it's passed to a linked ASM function as an INPUT vector, and you have 7 other places with different offsets that use different macros and different numbers.
      how TF am I supposed to know IF or WHERE those vectors collide, or who holds the critical data and where is it after this hellish pointer is just swapped to a different address of unrelated nature.
      WRITE UNDERSTANDABLE CODE YOU ABSOLUTE VALUE SQUARED MINUS VALUE TIMES CONJUGATE! // == 0

    • @drescherjm
      @drescherjm Před rokem +70

      LOL! I love it. With that said I try to write readable code with minimal comments because in 3 years I will have to try to figure out what the heck I was thinking..

  • @realroadrunnr
    @realroadrunnr Před rokem +5440

    I find the general rule "comment WHY you're doing something, not WHAT you're doing" is a good rule of thumb. Ideally the code should speak for itself but sometimes reality or co-workers get in the way of that ;-)

    • @yochem9294
      @yochem9294 Před rokem +47

      This! 🙌🏽

    • @dennisholmer
      @dennisholmer Před rokem +28

      I was gonna write this myself :)

    • @anthonyraymond1534
      @anthonyraymond1534 Před rokem +73

      I've always followed the "not what but why" rule. You hit it on the head.

    • @alexmercerind
      @alexmercerind Před rokem +1

      Agreed

    • @CottidaeSEA
      @CottidaeSEA Před rokem +36

      I wrote code today where a delete method explicitly stops the deletion of id 1. The reason simply being that I wanted to keep all settings in the database, but this specific one is one that simply isn't allowed to be deleted as it works as a global setting.
      That was promptly commented to explain why it was done. If someone at some point needs to make adjustments they will know if their changes will allow removal of that.

  • @truthmatters7573
    @truthmatters7573 Před 7 měsíci +532

    There are 3 types of comments. Comments that tell you:
    - how the code works
    - how to use the code (aka documentation)
    - why this design was chosen after mapping out the problem domain
    Only the first one can be mostly made obsolete by readable code.

    • @truthmatters7573
      @truthmatters7573 Před 3 měsíci +18

      @@SimonWoodburyForget Thank you for the additional information. These are indeed types of comments I had overlooked, because they're not a permanent part of the code base, but only serve as temporary placeholders. Still, thank you for mentioning them.

    • @benjaminv02
      @benjaminv02 Před 3 měsíci +3

      documentation is not a comment, only the last one I could consider but usually I wouldnt describe that in the code but rather on a content management workspace like Confluence. Or in the description of a specific issue on Jira

    • @benjaminv02
      @benjaminv02 Před 3 měsíci +3

      documentation is not a comment, only the last one I could consider but usually I wouldnt describe that in the code but rather on a content management workspace like Confluence. Or in the description of a specific issue on Jira
      And like Simon said, reminders to not change things or smth or to look at it later

    • @truthmatters7573
      @truthmatters7573 Před 3 měsíci +24

      @@benjaminv02 documentation that is part of the source code is kept in comments. Two things can be true at the same time. You can also have documentation that exists outside of source code which then would not be a comment.
      Obviously there are exists tooling around documentation and design/architecture, but if you wanna keep things simple and plaintext, then comments are a great place to keep all the knowledge in the appropriate context.

    • @Zicore47
      @Zicore47 Před 3 měsíci +7

      You forget "why" the code works :D

  • @LeFrog0
    @LeFrog0 Před rokem +2088

    "Do you guys find yourselves reading comments to understand code?"
    I work in numerical analysis, and most of the code I read is written by mathematicians. There are no comments and the variable names are often obtuse. So when reading someone else's code, I simply add comments, because it's easier than modifying everything... I try to follow your good principles for my own code, though!

    • @fizipcfx
      @fizipcfx Před rokem +115

      this, updating someone elses codebase requires way too much effort. But when you are actively developing things, its better for everyone to follow standards and good practices. I wish people could care more about this. My senior sees this as just beautifying the code. :(

    • @BorderKeeper
      @BorderKeeper Před rokem +95

      I think this is the key point why so many people argue with each other about this. In normal enterperise backend codebase your code is usually not doing anything that complex so clean readable code is sufficient, but when you are in game development, work with mathematicians who write code, or in general have a lot of math you will need those comments as a complex polynomial or some strange graph solving implementation are close to impposible to write efficiently.
      I will not accept comments as a crutch because the dev did not rewrite his not ideal implementation that went against other specs and got himself into a trap.

    • @ImperiumLibertas
      @ImperiumLibertas Před rokem +21

      @@BorderKeeper Bad code requires comments. Clean code does not. Point taken.

    • @driden1987
      @driden1987 Před rokem +18

      I don't work with mathematicians (thank God) because I know how they like to name things hehe.
      Whenever I find variable/method names that don't really convey meaning I just rename it using LSP, if I can and the codebase will allow it.
      If possible, "deobfucaste" as much code as you can, it will make it easier reading it in the future

    • @glinskiadam
      @glinskiadam Před rokem +7

      Wtf I'm stoned reading this and the quote got perfectly synced with the vid

  • @beclops
    @beclops Před rokem +1456

    I like this philosophy but people should be careful in practice assuming their code is self documenting to all. New devs/new hires may have a different threshold for this and I find that some higher level devs use the term “self-documenting code” to write complex and comment-less code with their egos while losing the practical point of it entirely. Either way I agree that documentation > commenting and writing self explanatory code should trump a comment (since many times they can be a code smell in its own way signifying over complexity).

    • @Grom1477
      @Grom1477 Před rokem +63

      Exactly. Only simple code need no comments
      And sometimes it is just not possible to express convoluted business logic with non-convoluted code

    • @pokefreak2112
      @pokefreak2112 Před rokem +20

      I disagree with this mindset. If new devs lack general knowledge they should pick up a course/textbook. If new hires require knowledge specific to your codebase that should be part of the onboarding process. What makes you think random comments sprinkled throughout a big codebase are an effective communication tool?

    • @hartmutbraun6712
      @hartmutbraun6712 Před rokem +7

      Exactly. In addition, code inspections are a great way to tell if your code is self explanatory. And the ultimate check is if a „new hire“ does understand the code. One problem here is that when an inspector doesn’t understand your code it is very difficult to keep the discipline to improve it AFTER you explained it to them.

    • @beclops
      @beclops Před rokem +121

      @@pokefreak2112 I mean you could extend this logic almost indefinitely. Why write simple code at all? Maybe they should pick up a textbook if they can’t easily parse my terse 1 liner. The goal when writing a large collaborative codebase should be to lower the bar of required context/knowledge as low as possible. This is exactly what I meant by devs being driven by their egos rather than utility. Obviously there are things they should just know, but the goal should always be to be as clear as possible through both self documenting code as well as well written documentation so that new hires and new devs can become effective members of the team quicker.

    • @sutetsu
      @sutetsu Před rokem +13

      Exactly. It's probably best to refrain from thinking in absolutes and adhering to dogmatic rules, period. Every project and every team bring their own unique set of challenges.
      In my organization, people may often want to use automation written by other teams, and often they can't be expected to have the same kind of expertise a dedicated developer would have. If some additional in-code documentation will make it easier for them to understand and modify the tool for their own needs I'd say it's fair game.
      As it was surely mentioned before, comments add maintenance load, so it's always a matter of balancing future costs against the present utility. While the rule makes sense most of the time, sometimes the scales tip the other way.

  • @petabyt
    @petabyt Před 7 měsíci +5

    Good luck maintaining a 400 line assembly file with no comments.

  • @yapdog
    @yapdog Před rokem +430

    No matter how well the code is written, comments are useful. It has to do with the fact that comments are rendered in a separate style which makes them easier to visually separate from code. So, the way I write comments is generally concise (i.e. single line) and right justified. I'm able to easily understand my code as a sequence of stages without reading through each function, enum, variable.

    • @elirantuil5003
      @elirantuil5003 Před 9 měsíci +11

      Easier for you, for me, when I see code with comments, it's mostly a distraction, because if it's trivial, I understand what im seeing without a comment, and if not, a comment won't make me understand it to the depth I would like to without reading the code. I have been part of the minimum comments school of thought for a while and my code got better for it.

    • @notmyregret
      @notmyregret Před 8 měsíci

      @@elirantuil5003 I've always been on the side that the more comments the better. But I also use VSCode, and have comments styled such that they don't distract. I imagine if you're using something like Vim it could be distracting.

    • @darkopz
      @darkopz Před 7 měsíci +9

      That’s not an absolute statement. The OP makes a great case as to why comments can be harmful. They’re not always useful. Especially if not properly maintained.
      Generally comments should focus on Why, not What. Code should be written so that the What is answered by the code. Which is what the OP is saying. They just missed another aspect, the Why.
      Generally the Why of the code won’t change. Because to do another Why, you’ll need different code that warrants its own Why explanation.

    • @Peter_1986
      @Peter_1986 Před 7 měsíci

      Comments are sometimes useful, however I personally think that it is very satisfying to try to find ways to make the code itself be as self-explanatory as possible.
      The "#define" directive is extremely useful for this purpose;
      for example, if I want to check for alphabetic characters, then I always use this definition:
      #define LETTER ('a'

    • @unclechaelsneckvein
      @unclechaelsneckvein Před 7 měsíci +15

      ​@@elirantuil5003Better for you. Not for anyone else who wants to read your minimal code.

  • @BigKevSexyMan
    @BigKevSexyMan Před rokem +266

    Here's what I usually do with comments:
    1) Describe the business purpose of a function or method. Fellow developers can usually determine what you are doing, but why you are doing it can be even more valuable and not apparent from the code alone.
    2) Describe assumptions and scenarios where the logic may break under certain data inputs (although it's generally better to just do proper exception handling) - For instance, I had to write a service that wakes up and copies a daily file from sftp and appends the date to a very specific name. However, there can technically be more than one file since it's just an sftp server. So we decided to just overwrite the old daily file when that happens. We describe that in a comment so when people look back at the code, they know it's intended behavior, and can react accordingly.
    3) Describe unintuitive bits of code you either can't re-write(ie. to make a third party's code work) or don't have time to re-write. Bring it up in code reviews! Maybe others will have suggestions.
    4) TODOs if you still have more development you would like to do at a future date. Do these even if you haven't submitted your code for review. You never know when you have to pivot to a new project/bug and will need to remind yourself where you left off. Obviously you need to make sure your code works properly before it gets submitted, but there will always be things that you would like to do, but don't have time.
    I think good comments generally arise out of a respect for time. Both yours and your fellow developers. If a comment gives them an easier understanding of what's going on, then do it. But don't waste their time with clutter.

    • @dandymcgee
      @dandymcgee Před rokem +13

      This is a really great summary about why we SHOULD write comments, sometimes. Nice one!

    • @TroyVan6654
      @TroyVan6654 Před rokem +2

      Points 1 and 2 are what documentation is for.

    • @Tenchi707
      @Tenchi707 Před rokem +13

      @@TroyVan6654 who creates documentation?

    • @scifino1
      @scifino1 Před rokem +12

      @@TroyVan6654 For point 2 in particular, sometimes you'll want to have an explanatory comment right next to the relevant bit of code, additionally to in the documentation.

    • @mbaer3592
      @mbaer3592 Před rokem +12

      Right. Too many people have as their personal credo that code "should be self-documenting" or that comments are bad because someone might change the code, making them stale. Then they use that as an excuse to not add comments to their confusing code. Sometimes the code itself isn't terrible, just hard to grok outside of an IDE, because the authors think you should always examine code with an IDE. However, version comparisons, web interfaces, and other situations often make an IDE inconvenient to impossible.
      As for stale comments, I find that a stale comment generally gives better information than no comment, especially if you know that comments can be stale. If you see it's stale, you can fix it, often with the help of version control to see where things went wrong.
      Also some applications and languages lend themselves toward functions having sections. Sure, you could make each section a function and then have it in or containing some huge class with everything in it, including variables only used for two or three lines. But it's often less messy and more readable to have informal stanzas of code headed by comments. If you choose not to read them, that's your business.

  • @MinefighterLP
    @MinefighterLP Před rokem +1995

    I always code and comment with the philosophy "Will i understand on a glance what this part does after a couple of months?". If you haven't touched a particular project in a while, its great to have good comments AND self explaining code (and a good documentation). Sure, things might be self explanatory while you write them, but it might not be for someone else reading/maintaining the code.
    Also, i have quite a bad memory, i quickly forget why i did things a certain way, so having detailed comments is quite practical.

    • @mackomako
      @mackomako Před rokem +29

      Comments lie.

    • @joshgribbon8510
      @joshgribbon8510 Před rokem +45

      I think lot of this just comes with experience too, early on I thought I needed to comment more, now I understand more implicitly and comment less - basically to enable IDE features, to link to documentation, or to explain why something is written "unintuitively"
      Similarly, I generally read the code first then go to comments afterwards for hints if I'm confused

    • @MrChaluliss
      @MrChaluliss Před rokem +82

      Yeah I don't think anyone should be preaching to reduce documentation for code. Having explicit code is great. But sometimes a comment here or there ties things together for a new reader or when you've been away from the code for a long time. The thing is, those small comments that tie things together don't take long to write either, because you write then WHILE you're well oriented in the code base, and thus can offer a quality perspective which may be hard to achieve without substantial time investment if you're not so familiar with the code base.

    • @curtiswfranks
      @curtiswfranks Před rokem +25

      Me too. I regularly thank past me for anticipating and addressing the issues which then-future me would be likely to not understand.

    • @IMBlakeley
      @IMBlakeley Před rokem +22

      I like to explain to future me what now me was trying to achieve.

  • @davidg5898
    @davidg5898 Před rokem +494

    I like everything about this in theory, but not in practice.
    For an ace dev team whose members are all on the same page, this advice could really streamline things. Unfortunately, not all coders are at that level, or on the same page. And even if you've assembled a dream team to work with, it's not going to last forever.
    Basically, what I'm saying is that you have to remember that you're dealing with humans.
    That said, there are certainly more intelligent ways to write comments and documentation. It's better to explain why a line/block/etc. exists than what it does.

    • @nyosgomboc2392
      @nyosgomboc2392 Před rokem +10

      Senior programmers tend to write more readable code. Also, code review could keep quality high enough so juniors won't mess it up too bad.

    • @iforgot669
      @iforgot669 Před rokem +3

      I have no problem maintaining this over many years with dozens of developers of varying skill levels. The less experienced a developer is they need more hand holding, group/pair coding sessions, longer code reviews. But on my team its expected that the senior dev's instill that knowledge to those who need it, its part of what makes you a senior dev. Its what allows me to have faith in the code we write, not the comments that explain poorly written and poorly tested code.

    • @pyrojkl
      @pyrojkl Před rokem +2

      I agree with this statement, working on a fresh codebase with a small team I will state this is achievable but there are plenty of cases in the code where a comment would have been helpful but I will also state again that it makes the code harder to maintain with too many comment when you are on a team that is doing true agile and you go back to make changes to the same code multiple times in a week or month and every time you may have to update the comment and the logic to help give context to the latest change otherwise eventually your comment becomes out of sync with your codes function...

    • @sorcdk2880
      @sorcdk2880 Před rokem +1

      Honest, I do to a large degree practice this style of comments into self-documenting code, and I have done so on practically all the code I write for quite a while. I think I made the transition when I had somewhere around 5-10 years of experience, so it is not exactly a beginner thing, as it requires you to be able to write high quality self-documenting code in the first place. If a programmer just writes comments, it is actually not so bad, as a more experience programmer can look at comments as code smells and then use those smells to refactor the code into higher quality self-documenting code. The recommended practice is a bit different than what this video describes though. First you need to learn to make lots of good comments, and once that is second nature, you go through the condensation step where you take your habits of writing comments and turn that into writing self-documenting code, first by refactoring and then later by going straight to high quality self-documenting code.
      With that out of the way, one should also realise that this only work for some types of comments (though before going through this, they will generally be by farm the majority of your comments). Currently the 2 most common types of comments I use are todos and reasoning explaining code. The latter is there not to make it easier to read the code, but rather to inform the reader/modifier of some subtle details or issues in the problem and/or implementation, such that they can account for that when they make changes, and they are there to also prevent common small changes that would not work due to those details.

    • @genechristiansomoza4931
      @genechristiansomoza4931 Před rokem

      Write a comment to give a reason why the code is written and other info stuff just don't write a comment just to describe what it does. Leave it for super complex logic.

  • @birdlegscass
    @birdlegscass Před rokem +114

    by far the purpose I use comments most for is as short headers to label sections of code. stuff like "jump" "collision" "take damage" etc. it makes my code so much more navigable, both for myself and others

    • @RobBCactive
      @RobBCactive Před 5 měsíci +18

      Labelling sections of code is a classic hint to give it a name in a function. Mostly I find code like that is duplicated in many similar places.

    • @birdlegscass
      @birdlegscass Před 5 měsíci +7

      ​@@RobBCactiveI write functions for pretty much anything I wanna use more than once. Everything else goes under a header

    • @silvercakes
      @silvercakes Před 3 měsíci +10

      @@birdlegscass Consider using a function even if you don't do it more than once. This makes it a testable unit. You are testing your code, right?

    • @MrMeow-dk2tx
      @MrMeow-dk2tx Před 3 měsíci

      @@silvercakes Most IDE programs allow you to test units like that without needing to make it into a function sometimes.

    • @calebfuller4713
      @calebfuller4713 Před 3 měsíci

      @@SimonWoodburyForgetIt is probably the main real use of comments 😂😂😂

  • @garrettgutierrez2677
    @garrettgutierrez2677 Před 8 měsíci +5

    I feel like all the advice from this channel is tailored for a perfect world. Yes, in a perfect world, code is written in such a way that it is totally readable, and so we don't need comments. But in the real world, you are going to right code that you know isn't very readable, or you are going to wrtie a line of code that, when someone else maintaining the code revisits it, they are not going to know why you are doing the thing you are doing or the way you are doing it. So in the real world you are going to run into a lot of situations where comments are totally appropriate.
    I have many of my own private git repos that even when I, the person who wrote the code, revisits them, I am not sure why I wrote it the way I wrote it. A small amount of comments every so often are going to be absolutely appropriate for any coder's toolset be they beginner or pro.

  • @Evigmae
    @Evigmae Před rokem +459

    I mostly write comments for future me in case I need to come back to a complex system after several months or even years. I find it's easier to grasp the context and intention of the code through a series of comment rather than just trying to understand what the code is actually doing. At the end both are necessary. But without the comments I would have to spend a lot more time trying to understand why/how I did things the way I did.

    • @firsfnamelastname8490
      @firsfnamelastname8490 Před rokem +10

      This means that your code isn’t self explanatory and of bad quality 🤷‍♂️

    • @Marco-dr2on
      @Marco-dr2on Před rokem +5

      That should be the documentation

    • @ZahrDalsk
      @ZahrDalsk Před rokem +170

      @@firsfnamelastname8490 No, it means his code is non-trivial. Anyone who skips commenting because "lol, makes sense right now" is an idiot and is just screwing over someone else who has to work on the code in the future - often, themselves.

    • @ImperiumLibertas
      @ImperiumLibertas Před rokem +7

      You should strive to take no longer than 5 seconds to understand what a simple function does. If it takes longer then you can either simplify the function or clean up the code. If done correctly your code should read very similar to english. Utilize variable names for values or things that have meaning but aren't expressive like at the start of the video where he uses MESSAGE_SENT = 5 to represent that status code.
      If you're in typescript or any language with similar features you can use a const object or a "const as const" to represent a set of values with meaning to remove any ambiguity in your code.
      Ideally, your code should be readable by someone who otherwise doesn't even understand the language you're programming in because the variable names are expressive. That last part is a stretch but a good goal to have.

    • @ZahrDalsk
      @ZahrDalsk Před rokem +75

      ​@@ImperiumLibertas My brother in Christ, just reading the initialization of a SINGLE Vulkan API object will usually take you more than five seconds.

  • @WalterWoshid
    @WalterWoshid Před rokem +779

    I understand why you feel this way, but before I was really good at what I was doing, I was heavily relying on comments. And I think that's the important thing, whenever you want people to possibly participate, in an open-source project for example, you want them to understand you and your idea. Especially because there are many beginners and sometimes before they can read code fluently, they want to understand what's happening there, especially for a complex project.

    • @stephenmorring3370
      @stephenmorring3370 Před 11 měsíci +34

      I think that's why the presenter made a distinction between comments and documentation (meaning documentation inside the code itself). The difference is, as explained, comments seem like an attempt to explain how the code works; documentation explains how, when and why use the code.

    • @WalterWoshid
      @WalterWoshid Před 11 měsíci +13

      @@stephenmorring3370 I insert as many comments as possible, sometimes even when the code describes already what it does. But I also add as much documentation as possible, for example: this code runs 200 other functions before running the next important function, and I will document that. I want people to know, that when they debugged inside one of my methods, they will know exactly why it was run.

    • @vern2982
      @vern2982 Před 11 měsíci +13

      @@WalterWoshid no comments has better readability. You can fully focus on the code whereas comments can be a distraction. Of course there's exception to this as mentioned in the last part of the video.

    • @conorstewart2214
      @conorstewart2214 Před 11 měsíci +31

      Open source projects are pretty bad and difficult to get into, especially when they have a rule of no comments. Some I have seen, big and popular open source projects, have no documentation and no comments, and the code is a convoluted mess, like having lots of functions whose only purpose is to pass a single pointer somewhere else, trying to find a specific piece of code to see how they do something is next to impossible, it is buried deep in there somewhere but it’s not clear where. I don’t know why they are so against comments, maybe it is because they do it in their free time and don’t care about making a good job of it, or it is maybe their “good code documents itself” attitude. At the bare minimum though every function should have a description of what it does and it’s parameters and what it returns. Yes comments can get stale but if you let that happen then you are just lazy, how difficult is it to edit the comments when you edit the code?

    • @Picksle
      @Picksle Před 10 měsíci +1

      dude don't write comments like he just said

  • @Peter_1986
    @Peter_1986 Před 9 měsíci +2

    There is something very satisfying about picking descriptive variable names, so that the variables themselves serve as "comments".

  • @murkorus7147
    @murkorus7147 Před 8 měsíci +74

    I think that no matter how simple your code is, it's always a good idea to comment a lot. You should be able to see at a glance what code does (If you're good), but good commenting can let you skim a full script and get a clear understanding of what exactly it does.

    • @mp_petrov
      @mp_petrov Před 2 měsíci +4

      ABSOTELUTELY FUCKING NOT!

    • @GreyDeathVaccine
      @GreyDeathVaccine Před 2 měsíci +4

      @@mp_petrovYou're not with your friends having a beer, behave yourself.

    • @mp_petrov
      @mp_petrov Před 2 měsíci

      @@GreyDeathVaccine 🫡

  • @TonyHammitt
    @TonyHammitt Před rokem +448

    I worked at a very small company where the code base was strangely devoid of comments. Just a reference at the top as to when the code as "cleaned up". Turns out that the guy who "cleaned up" the code was at one time the only programmer working at the company. He actually deleted all of the comments from the code and left that note as to where in the version history to look to see where the comments were, as a form of job security. He was the only one who knew how to find the documentation, so he could pull miracles out of his butt. Eventually I fired him for other reasons, but in converting the old code repository to a new system, I found the old documentation. Wish I could have re-fired him.

  • @John_L
    @John_L Před rokem +601

    I think it's dangerous advice to simply say "Don't Write Comments". Of course it is a good thing to equate constants, correctly type cast and use meaningful names for variables, procedures, functions, etc. That can significantly reduce the amount of commenting required to make the code understandable to others and/or to your future self. But anything other than the simplest code benefits from comments that explains the context and reason for doing something a particular way. Comments can also help those that come after you to understand coding tricks whose operation might not immediately be apparent but which are, for example, resource efficient - especially important for real-time applications. Having written code in a safety critical real time environment, sensible and considerate commenting is in my opinion essential.

    • @danielcommins1285
      @danielcommins1285 Před rokem +68

      Exactly 💯. I can tell the creator of this video does not work, or has not worked in embedded systems optimizing critical path or dealing with hardware access where the sequence of instructions matter and there are many timing/race condition issues. This video's title should be appropriately qualified as it's very misleading.

    • @crackasaurus_rox9740
      @crackasaurus_rox9740 Před rokem +6

      Junior devs get generalized advice all the time, and they break things learning where it doesn't apply. It's just part of not knowing what you don't know, and I would prefer it happens sooner than later.

    • @bernhardkrickl5197
      @bernhardkrickl5197 Před rokem +25

      @@danielcommins1285 He did explicitly point out that performance optimisations warrant a comment.

    • @danielcommins1285
      @danielcommins1285 Před rokem +41

      @@bernhardkrickl5197 he did, but didn't mention many other cases. The entire video is framed to suggest that the need for comments are very rare, but actually they're not in certain areas. The video misrepresents this and should mention only the programming areas which the creator is familiar and where this is applicable. The comments section is filled with many other counter examples as well.

    • @Rey_R_
      @Rey_R_ Před rokem +25

      The creator of this video never encounters an organization that is full of entry-level juniors who will later be the owner of your "complex" code aka code that they are unfamiliar with.
      Say you wrote an infrastructure/tooling code that involves calling shell commands, parallelization, etc. Those juniors don't really know the concept of such.
      Tell me a better way to tell them what it does other than commenting next to the line.
      Up their skill? Yeah, I'll apply as an instructor next time, not a developer.

  • @bcpeinhardt
    @bcpeinhardt Před rokem +56

    Fun fact: rustdoc automatically compiles example code in doc comments as integration tests, and you can use assert and whatnot, so code examples in comments don't go out of date because they cause a failing test :) It's a vibe

    • @jkf16m96
      @jkf16m96 Před rokem +5

      I didn't know that at the time and couldn't comprehend where the f my tests where failing, but my own unit tests didn't.
      Then I read more about rustdoc and it turns out, the examples were compiling hahaha
      Just fixed it and it worked:)

  • @TheSpidermint
    @TheSpidermint Před rokem +31

    I'm a technical director with over 20 years experience. Here are my thoughts: In real world business situations I would recommend always commenting. Don't assume your code is any good or makes sense to anybody else however readable you have made it. Also, it's important to explain why the code even exists in some cases. Documentation outside of the code can be used for this, but it is more helpful near the code itself, especially if it is non standard within any system or appears on the face of it to be redundant. Your code is almost always not production ready especially during phases of development, and this could be the entire length of a project. Comments can direct your team to changes required, refactoring or known issues. Code also often gets handed between different business and different devs/non-devs all with widely varying levels of skill and understanding. I think you should do whatever you can to make sure it can be understood on all levels. Just like your naming of variables video (which is great), there is now no need to shorten or remove things that are helpful. It's great as an exercise to encourage people to write more readable code for sure, but a well written comment leaves little room for misunderstanding. IMO

    • @donjindra
      @donjindra Před 3 měsíci +2

      Exactly. In the real world where code has a life between personnel, a good programmer tries to make his successor's life easy. There is no guarantee your code is going to be obvious to him. Comments should make it more obvious, save him some time.

    • @reindeerdashie
      @reindeerdashie Před 3 měsíci +1

      ​@@donjindra...or save her some time.

    • @donjindra
      @donjindra Před 3 měsíci +4

      @@reindeerdashie Obviously. But I don't pander to new language sensibilities.

    • @GreyDeathVaccine
      @GreyDeathVaccine Před 2 měsíci +1

      ​@@reindeerdashieLet's be real. How many female programmers do you know? I've been programming for 15 years. I've worked with 2. I can't count how many men I've worked with.

    • @calliopeshif7581
      @calliopeshif7581 Před 2 měsíci

      @@donjindra yeah, no, this is horseshit. Your response, I mean - not the reasonable adjustment proposed by @reindeerdashie .

  • @TheSpacecraftX
    @TheSpacecraftX Před rokem +326

    Good self self-commenting code can tell you what is being done. Not why it's being done. The WHY is the most important thing to comment. I've started 2 jobs in the last 2 years (and helped onboard people at both) and I can tell you it's a lot easier to make sense of existing code and use of unfamiliar libraries when there is a comment to explain why something has been done. Job 1 had must more extensive and versioned docs, job 2 had way better code standardisation and comments (with better code review). Job 2 has been much more pleasant. Sometimes I find strict commenting standards to be excessive but the lived reality is that sometimes having too many comments is better than definitely not having them where they should be. Doesn't help that both involved working with mathematicians, who are really bad at code readability on their first few attempts because they like to write code like maths and both don't use good names, and their documentation can get highly mathematically technical and hard to relate to the code.

    • @Tildryn
      @Tildryn Před rokem +14

      Yes, I add comments where I'm having to do code that may look unintuitive, but has to be done a specific way due to quirks in the system it's using. Unless you want the next developer along to change it and painstakingly debug to discover the quirks that led to the current approach being in use, you should document WHY it had to be done this way.

    • @anyadatzaklatszjutub
      @anyadatzaklatszjutub Před rokem +6

      on point!
      code should describe itself, sure, but it can not contain the context and fringe business reasons made in the pase, and so on
      arguably, this can live in the README, api descriptions, etc

    • @maskettaman1488
      @maskettaman1488 Před rokem +5

      The "why" should be in the documentation and left out of the code. Especially when it deals with domain/business requirements. The code is strictly the "what". Though in practice this isn't always feasible

    • @jinto_reedwine
      @jinto_reedwine Před rokem

      I agree, this is where I have landed as well. After I write something I read it back and clean up the code itself to make it more readable. Then I read over that code once more while asking myself if there is a specific intentional decision I made worthy of explanation.

    • @jordanb722
      @jordanb722 Před rokem

      I think this is an excellent take, especially "having too many comments is better than not having them at all". Unfortunately, this kind of advice is likely to be most taken by junior devs who won't have that skill, so we'll end up with arcane, poorly documented and reasoned code that will be a nightmare to follow in the future :(

  • @Sancarn
    @Sancarn Před rokem +246

    I think stating "Don't write comments" sets a dangerous precedent. Agree that in languages where you have Tests, Compiler checks and Linting that comments aren't required as long as you use easy to understand variable names etc. Ofc in some languages which lack these, comments become more valuable. Also, when something starts using hacky, black magic comments become vital in understanding the intent of the code.

    • @MagicGonads
      @MagicGonads Před rokem +12

      Which is said in the video (specific things for optimisation or obscure algorithms should have comments)

    • @Sancarn
      @Sancarn Před rokem +4

      @@MagicGonads I mean specifically the video author discusses obscure mathematical algorithms, not "hacky black magic"

    • @MagicGonads
      @MagicGonads Před rokem +12

      ​@@Sancarn both are examples of "hacky black magic" (from the perspective of reading the code)

    • @apexdude105
      @apexdude105 Před rokem +1

      Yes but the rule is don't write comment, there will be exceptions to the rule.

    • @Ouzzel
      @Ouzzel Před rokem

      Think the biggest thing I took from the video is don't make comments a requirement to read code unless necessary. Make the code itself more readable.

  • @lordkekz4
    @lordkekz4 Před rokem +82

    I largely agree that more readble code is generally preferable to unreadable code with comments. But I do think that especially in large functions where there are several "paragraphs" or steps being executed, short comments are useful to act as a sort of heading to more quickly orient oneself inside the function. Of course, it may be possible to split the function into several parts, but that can actually make it more obtuse (and more fragmented to read) if the steps don't make sense out of the context of the larger function.

    • @joneclegg
      @joneclegg Před rokem +8

      Why is the function so large? break it up and give the methods good names.

    • @stevenluoma1268
      @stevenluoma1268 Před 9 měsíci +3

      Sounds like you could probably have the steps as separate functions that are named so that the steps are obvious. Then if you still feel the need for a comment, it's probably a comment about "why" you're doing something, which can be a very useful comment. The docstring for this big function could say "here's what this function is for and all the steps that need to be done" without writing comments for each step explicitly.
      do_x = do_the_x()
      do_y = do_the_y()
      .
      .
      .

    • @jacknguyen5220
      @jacknguyen5220 Před 9 měsíci +20

      As someone who writes mathematical/logically intensive code a decent bit, I definitely find this true. Sometimes the algorithm itself may have a "step 1, 2, 3" and become somewhat long. Do those steps actually have names I can come up with other than "step1", "step2", "step3"? Sometimes but not always. Additionally, I think it's important to think about why we're separating something out into multiple functions. Does it make the code less DRY? Does it make the code more readable? Or are we doing it just because? I think it's worth realizing that the REASON we want to separate something large into smaller pieces is so that it's easier to digest smaller pieces at a time e.g. making sure we implemented steps 1, 2, 3 correctly by being able to see each individual step. With comments used appropriately, this can still happen clearly, and it becomes easy to see the major steps in a section of code as well as the code within those steps. It's easy to mention "best practices" and try to start with a solution in mind, but it's important to think about the actual problem being solved and if an alternative approach is more appropriate for a specific scenario.

    • @kingacrisius
      @kingacrisius Před 8 měsíci +14

      Did the first 2 replies even read the second half of the comment...?

    • @ben_clifford
      @ben_clifford Před 8 měsíci +12

      @@kingacrisius Exactly. The OP literally anticipated these kinds of replies and preempted them, only for his good efforts to be wasted.

  • @HilarionOfficial
    @HilarionOfficial Před rokem +4

    Bro, I swear every video you post seem like "hot take clickbaits" at first glance, but then they always deliver fantastic discussions of relevant topics. Another good one, keep them coming!

  • @ThePiachu
    @ThePiachu Před rokem +568

    One of my earlier jobs in coding was at a company that lived by the principle not to comment your code, since the code tells you what it does. However, when I talked to some other programmers, they shared this nugget of wisdom with me - "code tells you what the program does, comment tells you what the program should do".
    Just like you can have comments that don't align with what the code should be doing, you can have code that also doesn't do what it should be doing, aka bugs.
    So I'd rather have too many comments in the code than too few. It speeds up picking up the code since you offload re-figuring out what it does to the comments that have a better memory than you ever will.

    • @ElektrykFlaaj
      @ElektrykFlaaj Před rokem +48

      tests and their descriptions should tell what the program should do.
      Comments, if there are any, should answer WHY you implemented something the way you implemented it, not how you did it or what you did

    • @0oShwavyo0
      @0oShwavyo0 Před rokem +35

      Why are people obsessed with switching between files? Maybe instead of requiring my audience to open the specs or the documentation, I can put critical information for other devs right there in the source code where they’ll actually need the info. Especially if you’re using a dynamic language, comments with type info should be a general practice to aid the developer in reasoning about types given the lack of compile step.
      Documentation should also exist but should be for extremely detailed information and usage examples, whereas comments provide relevant high level context to help jog your memory or explain potentially confusing implementation choices

    • @gorgieboy10
      @gorgieboy10 Před rokem +48

      @@ElektrykFlaaj Relying on tests to document function of an app is insane.

    • @jonathanschober1032
      @jonathanschober1032 Před rokem +5

      @@0oShwavyo0 if you are adding comments explains types in a dynamic language, you are doing dynamic languages wrong

    • @ElektrykFlaaj
      @ElektrykFlaaj Před rokem +8

      ​@@gorgieboy10 that's your opinion. But fact is most large projects do just that.
      Tests describe what your program is expected to do, the implementation doesn't really matter as long as it passes all the tests.
      It can even be written by a junior with no clean-code knowledge. Just make it pass all tests and it's all good

  • @lydianlights
    @lydianlights Před rokem +109

    In my opinion, comments should tell WHY the code does what it does, not WHAT it does -- the code itself already tells you precisely what it does. That's the baseline principle I follow, anyway. "Don't Write Comments" is a catchy youtube title, but you should focus on writing useful comments, not absolutely no comments ever.
    Also, comments vs documentation seems like a false dichotomy to me. Comments are for people maintaining the code, and documentation is for people consuming the code. There is often overlap there, but it shouldn't be one vs the other. They have different audiences.

    • @nickdalfarra3887
      @nickdalfarra3887 Před rokem +7

      Great points. I was thinking the same thing re/ false dichotomy. In Python terms, this just feels like the difference between in-line comments and docstrings

    • @corvus8638
      @corvus8638 Před rokem +1

      It’s just a clickbait title to get more views

    • @epistax4
      @epistax4 Před rokem +3

      Small disagreement maybe. "why" (for high level why's) is the responsibility of version control. So the answer to "wtf is this?" Might be something about a cubic bezier curve decomposition with some theory and implementation detail. Good for comments. But why is this here? That's a requirement. I would hope a "blame" will trace it back to the original need, aka "why".

    • @skaruts
      @skaruts Před rokem +3

      The "what" is also important to document, sometimes. There's always places where it's just easier to read a comment explaining the "what", than it is to decipher the whole algorithm. You'll want to decipher the algorithm to know the "how", not the "what".
      It's just a matter of common sense, really.

  • @ansel_ale
    @ansel_ale Před rokem +1

    I am a heavy commenter, I like to comment what each function does and I like to comment each section of code (i.e Functions section, Main Code section, etc), I also like to comment what loops do or are intended to doing internally. I do find myself making several comments when coding and then when I feel like I'm done with making changes I start removing comments and consolidating them into one or a couple if really needed.
    I've always advocated for commenting your code, but until this video I think I had never really understood the difference between what I've been advocating for and what I've actually been doing and wanting more people to do, which is DOCUMENT their code!
    I have terrible memory and I find it better to read a single comment with the intent of what a piece of code does than reading the entire code, it also helps give more context to the code when actually having to read the code.
    Thank you for making emphasis on the difference between documenting and commenting, it'll definitely help my code be clearer in the future!

  • @drewmordecai4047
    @drewmordecai4047 Před rokem

    Amazing idea for the channel and great quality content, subscribed instantly. Looking forward to seeing more videos on code quality and aesthetics

  • @billy65bob
    @billy65bob Před rokem +72

    I tend to write comments for 6 cases.
    1. To remind myself why I did something (like that perf optimisation example), particularly if it's an awful kludge.
    2. Traps to watch out for (e.g. don't use X within Y or the system will deadlock)
    3. Non-obvious assumptions that cannot be easily tested for (e.g. Database Connection must have MultipleActiveResultSet enabled) - I usually assert it instead if it can be tested.
    4. For consistency's sake when I'm writing extensions for other people's code, and they've used comments extensively. I'm very glad for here
    5. I'm doing a verbose example to show someone how to do or use something.
    6. The what if I'm expecting myself or others to struggle following it in the future.
    For example, we had code that merged a bunch of flags together 2 at a time using very complex and contradictory branching operations.
    I optimised it into about 5 bitwise operations and 1 branch; it kind of looks like black magic if you don't understand the what...

  • @gracicot42
    @gracicot42 Před rokem +68

    The most important thing with comments is to explain the why the code do something, and should not contain what the code is doing. Those comments are the most useful to understand what was the intent of the developer and what is its mental model of the problem. Those are the things code don't convey, don't have much place in the documentation and can be critical to understanding for future readers. I think the most important message of this video is that comments are good to convey intent in a way that code don't necessarily does.
    Btw at 1:42, the unique is for unique ownership, as opposed to unique reference. You can form as many references as you want with *ptr and ptr.get(), it's kind of nitpicking but also important. I used to pass unique pointer by const reference everywhere to avoid forming non owning references. The problem is that those function had nothing to do with ownership, but yet received a reference to unique pointer. When I had a code where I needed to pass a simple reference to an object that wasn't in a unique pointer, I had to change all those function to remove unecessary ownership annotation.

    • @RagoziHD
      @RagoziHD Před rokem +8

      Completely agree. Comments for explaining HOW the code works should be few and far in between. You should be able to read your code like a book and understand what is happening.
      Comments for WHY this code was written in the first place (AKA business logic) absolutely need to be present in large and complex enterprise-level codebases. When you step up to enterprise-level, that is a whole different ballgame of readability and maintainability. Documenting the business needs behind why something is written the way it is is CRUCIAL when developers come and go and knowledge needs to be transferred and maintained.
      Business logic comments can be the difference between a production incident or not.
      I like where OP's head is at - just wish he had mentioned business logic here.

  • @morpheon_xyz
    @morpheon_xyz Před rokem +2

    I've started learning C++ now over the past few weeks, and currently my comments are there to help me remember what's what, so they're essentially like notes with the code I'm writing, but that's just on the study side of it. Otherwise I haven't really bothered adding comments to my assignments as they're self explanatory at the moment, but hey I totally understand what you're saying, and it makes sense. Also, I will agree that even though the code change, comments don't always change in a parallel fashion, so that's a good point you brought up too

  • @blahblahdrugs
    @blahblahdrugs Před rokem

    I am a novice programmer, learning right now. I would really love to see some more content from you. I really like your style and advice. I keep saving these videos so that I can reference them down the line. I want my code to look like this.

  • @gorgenfol
    @gorgenfol Před rokem +57

    I agree that documentation comments are the one kind of comment you should write consistently and frequently, while all other kinds are an indicator that you're probably doing something bad.
    Though I'd point out one thing, no matter how readably a piece of code is written, natural language is still easier to read. And as a library user it's just not convenient to look at the implementation to figure out what's going on.
    If we write code for the reader, then documentation is crucial.

    • @gorgenfol
      @gorgenfol Před rokem +1

      So what's good documentation? I personally try to write documentation as a specification so my reader knows exactly what they get. A spec doesn't specify how to implement the code, but it does specify what should go in and what that results in. Add an example of when it's appropriate to use and voila

    • @jeremypnet
      @jeremypnet Před rokem +2

      @@gorgenfol the documentation tells the reader what they *should* get, not necessarily what they will get. As a simplistic example, if the documentation comment says "return a prime number in the range 2 to 23" and you get 12 out, there's your bug.

  • @dexterantonio3070
    @dexterantonio3070 Před rokem +29

    Another reason for writing comments, which one absolutely should do, is for adding in citations. If you are implementing a modified distance transform link to the source. If you are adding a bug fix and the code seems a little strange, add in a comment explaining the motivation and cite the PR. If you steal a block from stack overflow add in a link to it Ada comment and explain why you copied it.

  • @ViniciusNegrao_
    @ViniciusNegrao_ Před rokem

    I'm very happy that I've already been doing almost eveything I've seen on this channel. I really strive to make my code as readable and easy to understand as possible

  • @DoomRater
    @DoomRater Před 11 měsíci +3

    Bisqwit had a lovely little bit of insight on comments- he writes comments to explain why the code is written the way it is, not what it does. I like that approach. Making the code read as much like native language as possible is an art form and I think an underrated part of code readability as well.

  • @keithmaggio7755
    @keithmaggio7755 Před rokem +602

    If you're working in a group, please write comments. Not everyone "reads" their code the same. I worked with a guy who refused to let his lines of code go over 80 characters. His code was full of constants and typedef statements so it looked like "C::N::S.A(x,y,Z);" and such. He said it made the code look so much better to him. He no longer works for us. The code you'll write will look as readable as the nodes you keep, so, please, if you code in a group, write comments ffs. Code as if the guy after you is a psychotic that knows exactly where you are at all times.

    • @MaeLSTRoM1997
      @MaeLSTRoM1997 Před rokem +95

      i think that guy's problem was not his refusal to break the character limit, but the way he sought to meet that goal. many public codebases stick to 80 character limits and are still very human readable.

    • @daemetheus
      @daemetheus Před rokem +48

      This is also a lack of having a common style guide. Worst case, just use Google's style guide as a foundation and then go from there as your dev team needs change what is considered acceptable (and readable) to the team.
      With everyone having their own style of programming (i.e., their "voice"--you can tell who wrote what), if everyone is at least following some minimum standards, then the code is understandable by a larger majority of the team, because everything foundationally looks and reads with familiarity.

    • @meingutername2158
      @meingutername2158 Před rokem +34

      I disagree. In particular if you are working in a group, code should be readble and understandable. That 80 characters limit is good for readability. Of course the specific style of writing code is not well readable, but rather than adding comments, I't prefer more readable code.
      Of course it depends a bit on the language. If you're writing ASM, comments are something different.

    • @WonkoDerVerstandige
      @WonkoDerVerstandige Před rokem +28

      I find that people who write unreadable code also write unhelpful comments, like /* check if status is 4 and set sent flag */

    • @veto_5762
      @veto_5762 Před rokem +11

      Looks like the kind of guy that verify if his code its readable by checking if it sticks to the rules rather than actually reading it
      Ngl im not an expert, but i feel there's a difference between code looking clean and being actually easy to read

  • @daggerball
    @daggerball Před rokem +250

    I rarely write comments, but I found that writing down essays about the problem you are facing is very helpful. Each time I feel that I stuck on something I try to formulate the problem and write it down, include some code snippets. And I usually found myself with 5-8 pages long description of the problem and different ways of solving it, their pros, cons, and why none of them are going to cut it. It very much helps me to track down the root of the problem. I think that keeping the reasoning behind specific design choices close to the code (maybe in separate files, but they should be easily accessible for anyone who works with that code) is especially important in the early stages of development, when interfaces and other specifics are not that rigid. And that code should not be the first thing to write, when the codebase face the need of change.

    • @jmr218
      @jmr218 Před rokem +9

      This. If you can abstract the essay and make it accessible to non-technical readers then you can build a LOT of good will with management & product folks at your company when trying to change the direction of a project.

    • @xomiachuna
      @xomiachuna Před rokem +9

      That is pretty much a description for literate programming

    • @thunder____
      @thunder____ Před rokem +5

      Even as a one-person operation, I've found this to be true; on a few occasions when facing complex issues, I've found myself typing up an essay to explain the issue and planned course of action for myself and figuring out the answer along the way, or typing up an email to my dad to ask his advice and figuring things out on my own while explaining the possible solutions I have in mind
      (and as a tangent to that last point: when reaching out for help, I always try to include my analysis of all possible solutions I can think of, and most of the time, when typing out that analysis, something will click for me and I'll realize I don't need to ask for help. But including that kind of thing in the final email on the occasions where I don't end up figuring it out in my own also 1. shows the other person that I really tried to solve it on my own and I don't mean to waste their time, and 2. opens up the floor for more learning opportunities because any flaws or missing links in my thought process can be corrected to help me solve similar problems in the future, so I highly encourage this practice)

    • @stevenluoma1268
      @stevenluoma1268 Před 9 měsíci +1

      If there's a comment and it says "why" something was done, I'm almost always okay with it. It's when comments say "what" code does that makes me go "you could've just refactored this to make it more readable." So unless the comment says "there was no time to make this more readable" with the "what", I'm usually interested in a refactor asap.

    • @tilmanrotationalinvariant2257
      @tilmanrotationalinvariant2257 Před 9 měsíci

      This is what happens automatically if you try to write good PR's. I'm trying to be very scared of obvious solutions of my reviewer, so that I have to detail everything I tried and excactly why it didn't work. You learn a lot about the problem and also you learn to cite standards and look up implementation details. Often problems arise because you are stuck in one mindset or you just assume you know in what direction the problems lies.

  • @derekbelanger7839
    @derekbelanger7839 Před rokem

    Well organized things are often self-descriptive. This is true even in the natural world, if we dare to use that as a guide. Another thought comes from this quote: "There is nothing complicated. There are only things poorly designed or misunderstood." We may extract from this the idea that what is well designed is easy to understand. This speaks to your passion for excellent code. The other part of the quote reminds us that we may fail to understand even simple things. Perhaps this is why some value comments. It acknowledges that we need each other and can do something for one another. I love your videos. Please keep making them!!!

  • @malcolmphillips5537
    @malcolmphillips5537 Před 10 měsíci

    I follow all of this already 😎
    You briefly touched on one point I was going to raise and that's that comments are needed to explain WHY the code does what it does. Any good programmer can figure out what it does, but it can be impossible to figure out WHY.

  • @skaruts
    @skaruts Před rokem +249

    It took me much, much longer to decipher the code in your second example, than it took me to read the comment you deleted from it. I understood what was going on there much quicker from the comment. Point being, an outsider reading your code might thank you if you use comments. Heck, you might thank yourself six months later reading your own code, because comments make it less time consuming to catch up to what the code does, or why it does what it does. Comments have a purpose.
    Comments can be outdated, but it's not that frequent, in my experience (I've had some in my own code, but not often). Either way nothing is perfect. Code can lie as well. Dead code can exist. Not everyone uses an editor that detects it.
    And separating everything in descriptive functions isn't always feasible, and sometimes refactoring is just asking for bugs. But everything has its pros and cons, and the more you separate the code into functions the more you make the code harder to follow. You'll be fragmenting the implementation such that it'll be harder to make sense of it, requiring more going back and forth in the code to put the pieces together.
    Extremist perspectives are usually not quite right. The right answer usually lies somewhere in the middle. Everything has its pros and cons.
    Code documentation is terribly cluttering... And it can be outdated as well.

    • @benismann
      @benismann Před rokem +15

      also wouldnt adding more variables and stuff to make code "cleaner" like that take up more memory?

    • @MagicGonads
      @MagicGonads Před rokem +11

      @@benismann each level of function in the execution path also has the overhead of a function call (allocate stack memory, jump to new location in executable code, do other calling convention things)

    • @MagicGonads
      @MagicGonads Před rokem +4

      But the benefit you get from all that decomposition is far easier debug, every time an error happens you know exactly the code path it occured in, if you split up your expressions and put checks in between (more runtime overhead) you know which expression failed instead of a cascading error.

    • @MagicGonads
      @MagicGonads Před rokem +5

      This tradeoff between runtime efficiency and debug efficiency is solved mainly by build systems that take your code (with all the debug stuff in it) and squash it down into something without it, that runs way faster (even if it's not being compiled to machine code). But in practice you probably want to leave some debug in the production environment so you get solid logs and reports to work off instead of only those that come from your own testing, especially as runtime is less important as hardware and underlying libraries get more efficient and robust.

    • @skaruts
      @skaruts Před rokem +16

      @@benismann yes, but to be fair, the difference is probably negligible. I mean, if you created 200 extra variables of 32 bits each, that would only cost you 800 bytes of memory.

  • @annakrawczuk5221
    @annakrawczuk5221 Před rokem +48

    I found that writing comments is important when learning programming as a whole or a new language. I find it easier to remember what the functions I use do, when I explicitly write it in my own words

    • @luke2042
      @luke2042 Před rokem +2

      Me too. It helps me with debugging as well.

    • @dss539
      @dss539 Před rokem +1

      You might try finding a way to make your code read more like your prose.

    • @melanp4698
      @melanp4698 Před rokem +3

      You should write a good docstring for the function itself that explains what it does and if it has significant input/output parameters, how they're treated. You shouldnt hide all these things inside the code itself.

    • @MagicGonads
      @MagicGonads Před rokem +1

      And you are the target audience of this video, it's not targetting people who are well experienced in the industry working on projects will established guidelines and constraints, it's trying to prevent new coders from keeping the mentality you currently have, and that's exactly the stigma ('code smell') associated with lots of comments "the developer doesn't even understand their own code so they had to write all this redundant fluff"

    • @annakrawczuk5221
      @annakrawczuk5221 Před rokem +1

      Thanks for replies. I'll see what I can do

  • @pafnutiytheartist
    @pafnutiytheartist Před rokem +2

    I like this approach: the code should tell you what it does, the comments should tell you why it's doing that.

  • @marccygnus
    @marccygnus Před 7 měsíci +5

    Interesting video! I generally agree that comments should have high value when used, but I'd hazard a guess you've never done serious embedded development. Comments are essential in an environment like that, and it's not just "why is this written like this", it's also "what does this do". When you have a ton of registers to configure, asynchronous setup steps, and interleaved DMA and control operations, those comments are gold. Also a pain to keep synchronized with code, sure, but many times even out of date comments can help solve a problem.

  • @mertturkmenoglu99
    @mertturkmenoglu99 Před rokem +17

    I would like to rephrase this idea. Instead of "don't write comments", I'd like to say "don't rely on comments". You can use comments if other means to convey a message fails.
    Adding a comment to explain something shouldn't be the first tool we use. When other ways fail, then as a last resort we can write comments.

  • @gigatesla
    @gigatesla Před rokem +38

    I work in a few C++ codebases where performance is really important (EDA for chip design), and some of the algorithms and data structures we use can be rather abstruse - lots of bit twiddling hackery, for example. Comments are important in cases like that.

    • @rasmusgerdes6822
      @rasmusgerdes6822 Před rokem

      I only recently started learning C/C++, more as a hobby than for my profession (tho it might get handy, since I could deal with PLC programming in the future, albeit I'd most likely use ST/SCL one those).
      My question is: would you consider additional variables for the conditions in the example with the if-loop at the beginning as a waste of resources? I mean, for most applications it wouldn't probably change a thing, but what about small embedded systems? I'm really not sure about the consequences of a few more byte here and there for every loop, but what I'm pretty sure about is that the smart use of #define for the preprocessor should always be an efficient practice to make the code more readable. What's your opinion on this topic, regarding performance issues?

    • @hawks3109
      @hawks3109 Před rokem +4

      @@rasmusgerdes6822 C++ offers a ton of compile time/compile optimized tricks that allow you be quite expressive while the generated code is relatively unchanged. The biggest help here is learning the language environment and the inner workings so that you can be expressive without the cost of performance. Now granted this is not always possible, but the vast majority of the time it is. For example, often times multiple var assignments will simply be compiled down to the end var being the only assignment that actually happens in the executable.

  • @kennethbeal
    @kennethbeal Před rokem

    Nice. In my career, I learned to write two documents: the "design document", and the "functional specification". The slide @3:40 rhymes with that.
    The former is "how it looks to the end user" and the latter is "what we'll use under-the-hood to make it work."
    Writing *both* of these, before beginning a project, has helped with success.
    Another way to look at it is, describe the "form" and the "function" and you've mapped out most of what you're working towards. Love the cartoon at the end as well!

  • @fredflintstone505
    @fredflintstone505 Před rokem +4

    I use comments all the time. It’s very helpful to read a quick line describing what the code is doing so I don’t have to spend a bunch time deciphering the code that I wrote months ago or years ago.

  • @JornamMusic
    @JornamMusic Před rokem +57

    I've had applicants that take self documenting code a little too seriously and didn't add comments to function declarations. Please do both.

    • @scragar
      @scragar Před rokem +5

      If you've done it right the only things you should need for method comments are sample usage(which is better in tests IMO), and @see/related documentation. The method signature should be obvious enough and the method named clearly enough no one needs to read anything more to use it.

    • @user-zb8tq5pr4x
      @user-zb8tq5pr4x Před rokem +22

      @@scragar You've never written a c program I assume. Yes it is "technically" possible to write completely explanatory argument names, but since 5 word variable names are slightly impractical and a comment costs literally nothing, I don't see the point.

    • @jamesfaucher4588
      @jamesfaucher4588 Před rokem +3

      I hate function declarations because they don't actually tell you anything and people don't update them. I see: string customerName //Customer's Name all the time. It bloats the code making it harder to skim through code to find what you're looking for. Using the IDE's Search function for everything slow you down.

  • @xBZZZZyt
    @xBZZZZyt Před rokem +4

    00:44 note: "and" doesn't evaluate right side if left side's result is false
    "or" doesn't evaluate right side if left side's result is true
    putting stuff in variables will always evaluate right side of "=" no matter what code runs after
    so new code with variables in some cases does unnecessary computation

    • @GrantGryczan
      @GrantGryczan Před rokem +3

      This doesn't happen if you check the condition (ideally with an early return/continue) before defining the next variable.

  • @guillermoch
    @guillermoch Před 8 měsíci

    Well, understanding the code is like having to watch an entire movie, but sometimes you only need to know what the movie is about in a couple of minutes instead of spending 1.30 hours of whatching.
    Your videos are awesome, thanks! Suscribed.

  • @DMibis
    @DMibis Před rokem

    Loves these type of videos, they are calm and very interesting to listen to :D

  • @neirenoir
    @neirenoir Před rokem +34

    I remember that, while I was programming a billing system for a warehouse control software in my old job, that I found an edge case that could break the software in case an user attempted to do that. We decided not to fix the potential bug because it was nontrivial, and chances are no user would need to do something like that.
    Long story short, one of the newer clients had that exact edge case. By that time, I was already long gone from the company, but I still kept in touch with my old boss, and I learned from him that they found I left a comment explaining what the edge case was, why it happened and a general overview on what had to be done to fix it. I saved them days of debugging with a single comment.
    Always strive to write self-documenting code, but never say no to comments: they save lives.

    • @fltfathin
      @fltfathin Před rokem +4

      esp if something is deliberately built to break or edge case not to be fixed like this.

  • @rcnhsuailsnyfiue2
    @rcnhsuailsnyfiue2 Před rokem +52

    Declarative programming styles make comments far less necessary, so I always try to avoid writing in an imperative style. I do still make a habit of adding a 1-line docblock to each method, if the method is named well it’s not really necessary but I also like it when my IDE gives me nice human-readable hints as I’m referencing the function from a different file context.

  • @gogl0l386
    @gogl0l386 Před rokem +1

    "Comments can lie, code can not" this dude got the best quotes about coding honestly

  • @Tome70
    @Tome70 Před rokem +1

    I am amazed by the video editing quality and effort you put into this. the code examples and how they transition is super smooth. Really great job!
    Can you please share what tools you use for video/audio editing? any reference tutorials?

  • @aeroandspace
    @aeroandspace Před rokem +23

    Your videos remind me a lot of when I was training martial arts; often times there is a comfortable way to do something that isn't correct, but you don't run into the reason why it's bad while you're training. Ensuring that you keep proper posture and form may seem arbitrary, but it forces you to work the right way and build the muscles that, at the end of the day, you actually do need.

  • @Pretagonist
    @Pretagonist Před rokem +72

    Good code is better than comments for sure. Sometimes you don't have time to write good code.
    The main exception where I think comments are a must is when you have to do strange things to work around limitations beyond your control. While commenting the HOW should be avoided , commenting the WHY is important. Multiple times I've come across code that seems wrong, spent time trying to redesign it, only to hit upon the same limitations that the original dev did and ended up reverting back to how it was. A WHY comment would have saved me hours. They WHY is also a lot less likely to change than the HOW so it has a better protection a against being a buggy comment.

    • @loucantnot
      @loucantnot Před rokem +9

      This ^ is a very important... comment :p
      Seriously, "do not reinvent the wheel".
      This channel has very interesting "hot takes", and I do like to be slightly challenged when I watch om of these videos and ask myself "Why does it irks me ? Is it because this idea is right and I'm of "bad faith", or is it really controversial ?".
      However in this specific video's case, the advice of commenting less only works in, well, specific cases.
      It would be really nice though to reach a state of the industry in which there would only be working production environments where such elegancy and distributed trust on the meaning and intent of code & comments were the norm.

    • @johannestafelmaier616
      @johannestafelmaier616 Před rokem +3

      The "WHY" vs "HOW" would probably solve the biggest problem with comments.
      However your statement "Sometimes you don't have time to write good code." slightly upsets me.
      You are obviously correct in that statement, but I feel like it should be stated that such "times" should be avoided at all costs.

    • @Razbewy
      @Razbewy Před rokem +3

      this. If given all the time in the world, I'd need no comments. But it simply isn't the reality. The world needs more comments.

    • @Pretagonist
      @Pretagonist Před rokem +1

      @@johannestafelmaier616 I'm working on codebases sometimes 15 years old (or even older). If I have a ticket to fix a small bug or add a minor feature I don't have time to get the entire thing up to snuff. I'll just cobble something together and move on.
      I still try to remember to write a comment regarding why I did it that way though.

    • @richardpaulhall
      @richardpaulhall Před rokem +1

      "Sometimes you don't have time to write good code."
      > I -might- do that on a patch that is tied to a real deadline.
      The Invoice Job starts at noon and a hot fix is needed NOW!
      I will commit the patch. Then I will add the comments and commit the code again to get the comments in the code base.
      But for a deadline days, weeks, or months away, I put in comments.

  • @johanlarsson9805
    @johanlarsson9805 Před rokem +1

    Still waiting for that Dependency Injection video! You do great matterial!

  • @mennovanlavieren3885
    @mennovanlavieren3885 Před rokem

    Thanks for this video. I'll be using this as a reference point to explain these concepts to others.

  • @Lord_Vertice
    @Lord_Vertice Před rokem +15

    I'm implementing a specific algorithm as a side project. The algorithm has 6 distinct steps. Each step (except for 1 small one) is its own function, and the main function calls them 1 by 1. There are some side steps that are executed between the functions though, which allows me to reuse some functions elsewhere, so this means that each step in the main function corresponds to about 3 simple lines of code. To make it obvious which lines correspond to which step in the algorithm spec, I add a simple // step x comment at each step in the main function.
    I could've named the function stepOne, stepTwo, etc, but then it wouldn't be obvious what the function does unless you check the external algorithm spec, which isn't mine. So I decided to name the functions according to what they do on their own, as you do, and use comments in the main function to make it easier to comprehend how my code follows the external spec (or sometimes deviates for performance reasons). My main function now reads almost exactly like the algorithm spec, with each of the steps in their own functions, and comments making it clear what step we're at and how, if at all, I had to change it.

    • @NicolasChanCSY
      @NicolasChanCSY Před rokem +5

      I scroll through the comment section to find this, especially when comments are often coloured differently in IDEs, which aid marking sections of my code.

  • @CryShana
    @CryShana Před rokem +25

    "Human-readable" code is mostly always best and requires no comments because it's self-documenting (except maybe for some high-performance code) - and I have already noticed some people mentioning it's important to sometimes comment WHY some code is running rather than WHAT.
    I agree with all that, but I wanted to also add that I sometimes use comments to highlight certain code regions better - of course when I can, I split them into functions instead - but other times, in bigger functions that are harder to split (like some algorithm or high-perf code), I like to add comments what happens at which part - just to make it more readable. You can immediately spot which part is what because the comments are a different color from the rest of the code - it's like a header. And this usually helped me a lot with navigation when dealing with long functions. And these comments are usually quite high-level description of what is happening - so it doesn't happen often that code wouldn't match the comment.

    • @Tynach
      @Tynach Před rokem +3

      This is what I do as well. I wrote a lot of colorspace conversion code in GLSL for fun a while back, and for each shader that exhibited a particular conversion I'd have a comment at the start of every high-level 'step' of the algorithm. When I'd come back to it months later, it helped tremendously with seeing where each step took place and how the steps fit together. Sure, each step was usually multiple lines of code, but the comments let me abstract the nitty gritty details until I narrowed in on the section I was wanting to read.
      Even though the comments were the, "What is done," variety rather than "Why it's done," it was still immensely helpful because it bridged the gap between the high-level algorithm and the low-level implementation of it.
      Also, most colorspace conversion algorithms that I found documentation for use a LOT of single-letter variables in the documentation.. And for the most part, I worked really hard to translate them into higher-level and more meaningful names. While this helped me understand what was going on in my own head, often the single-letter variable names in the math documents were consistent and well-known between sources.. And I'd have to frequently have to remember which single-letter names belonged to which 'meaningful names'. So.. I sometimes ended up adding comments next to each meaningful name to say which single letter it relates to.
      It also bit me in the ass when I'd find out later that I misunderstood the meaning of a variable, and have to figure out a better high-level/meaningful name for it and then change it everywhere.
      ... There's a reason why I haven't yet made my CIECAM02 shader on ShaderToy public. Sooo many variables and constants and constants that turn out to actually be variables and variables that have subscripts for different instances of it and just... Eugh. I've found out many times while writing it that I got the meaning for something completely wrong, and I'd change the comment, but forget to change the name, or I'd find out that the name was fine and technically correct but highly misleading, so it makes me want to figure out a different name, but no other name really fits, and just...
      Eugh. I don't know if I'll ever finish that one.

    • @melanp4698
      @melanp4698 Před rokem +1

      If you write a large block of **** or something with "Outputting to file" etc, i wouldnt really call it commenting per se, since it's more just a headline that this next block of code "does it's own thing" pretty much. I think that's decent practise to do (unless you could just move that block to its own function).

    • @Tynach
      @Tynach Před rokem

      @@melanp4698 That sounds like you're saying, "If you use comments correctly for what they should be used for, that's not really using comments."

    • @melanp4698
      @melanp4698 Před rokem

      @@Tynach Well kinda yes, kinda no, because it becomes more like structural hints than actual code comments.

    • @Tynach
      @Tynach Před rokem

      @@melanp4698 I mean, if you think about it, a 'comment' is - linguistically - a side note; an 'oh by the way...' sort of thing.
      If you're adding structural hints, you're saying things like, "Oh by the way, here's where we start this thing," or, "Oh by the way, here's this part."
      If that's not 'commenting code', I don't know what is.

  • @scheimong
    @scheimong Před rokem +1

    The way I like to put it is "write declarative code". Basically, most of your lines should look like `let = ` because it's much, much easier to understand and change. Keep mutations and empirical statements to a minimum, and your brain will thank you for it 6 months later. Coincidentally (or not coincidentally), this is exactly the style heavily encouraged by functional programming, which is part of the reason Haskell and Rust are so beloved by their users.
    Of course not all languages allow you to do this, which actually makes it a good measurement of the ergonomics of the language. Did I mention Rust? Because in my biased opinion this is a key factor to Rust's excellence (maybe even a greater factor than its flagship feature of memory safety).

  • @joesunshine4006
    @joesunshine4006 Před 8 měsíci +1

    It’s a lot harder to express my rapidly dwindling sanity without comments though.

  • @theisegeberg
    @theisegeberg Před rokem +21

    I suggest reading the book "A philosophy of software design". It's got a great take on comments.
    Also I think it's worth talking about literate programming. Which is completely different from comments. But the general idea of writing down what you're intent in human language is before writing code is really rewarding.

    • @patrickcorliss8878
      @patrickcorliss8878 Před 11 měsíci

      Do you mean "literate programming" introduced in 1984 by Donald Knuth?

    • @theisegeberg
      @theisegeberg Před 11 měsíci

      @@patrickcorliss8878 Yeah I think my autocorrect got me. :-)

  • @iau
    @iau Před rokem +20

    My key takeaway here is: Code _should_ be self documenting, but that doesn't mean code already _is_ self documenting. Making code self document means adjusting how you write code. It takes more work, but it's for the better.

    • @rosiefay7283
      @rosiefay7283 Před rokem +4

      Self-documenting code is an unrealisable ideal. The code says what's going on at the rock bottom level. The comments are for saying what's going on at a higher and/or more abstract level.

    • @hawks3109
      @hawks3109 Před rokem

      @@rosiefay7283 It's unrealistic in some places, but I work at a top company which attracts some bright engineers. They rarely have to comment code and I often update code I've never seen before with little to no issue because of how well their code is written. It is possible, and easy after some practice, to write easy to read and understand code. Almost all code should be straight forward and easy to understand.

    • @iforgot669
      @iforgot669 Před rokem

      @@rosiefay7283 Your entire design philosophy is wrong if your code doesn't reflect the current abstraction level. Low level methods do low level code. Higher level methods call lower level methods. All methods should be at a single layer of abstraction.

  • @ruisantos7363
    @ruisantos7363 Před 8 měsíci

    I'v seen this video 8 months ago and my code has been improving since.

  • @videolabguy
    @videolabguy Před 11 měsíci

    Thanks for another great video!
    I used to write machine control code, front panels and the like for video equipment. (late 1980s) The first iteration was literally all comments, describing the flow charts we used in our engineering sessions. YES! Flow charts. I then translated that to prose. Would test chunks of it in BASIC(of all things!) to debug the algorithms, then would recode to assembly language. So, I would have three sets of source. ALL comment file, BASIC test files, and final ass'y code. I know you are reaching for the air sick bag. For me, and the very small company we worked at, this was relatively efficient. Realize that, at that time, there were not many well versed programmers going into that particular specialty. Coding today may as well be written in Romulan. It outpaced my skill set decades ago.

  • @JochemKuijpers
    @JochemKuijpers Před rokem +80

    Code comments seem almost useless on small projects or in small teams, where everyone can just intuit how code relates to the problem that the project is trying to solve. But on large long-lived code-bases with lots of decade-old legacy code, and where every team has their own specialized corner of the code-base and rarely interact with other team's code, having code comments to justify the *reasoning* that the code should do the thing it is doing, is insanely helpful. You no longer need to walk over to the other team and go: "Hey I was reading through your code and I'm wondering, why do we need this if-statement?", or worse, reach out to a retired or ex-employee. The code comments will just tell you why it is set up the way it is, and if that reasoning is no longer valid, you can use the comments to justify your need to refactor.
    It's an excellent way of preserving knowledge right there in the code. Sometimes knowledge *isn't* about the high-level architecture, but about line-by-line decisions made by the programmers who wrote and maintained that code, and for those use-cases, inline comments are still very useful.
    I agree a comment should never reflect the meaning of the code that follows it, but as of right now, I don't think there's a way to directly make a compiler understand design decisions, reasons and intent. Those comments I think are valuable, especially in large code bases. Yes, if you can refactor code to remove ambiguity and make code carry its meaning better, you should do that of course, but there are all kinds of pieces of information that you can't encode in compiling code, and for those (assuming they're important enough), comments are the next best place to put them.
    Anything that's externally relevant should go in code documentation (javadoc, etc.) or higher level architecture descriptions (readme/docs). But there is a category of information that is only relevant within a (private) method, that still carries importance. And there's certainly an 'art' to choosing the right signal to noise ratio. For simple shell code connecting high level systems, you probably don't need much code. For low-level optimized routines, there may be a comment before every 'paragraph' of code, or even every line. It really depends on context.

    • @danniejuge1941
      @danniejuge1941 Před rokem

      The reason why rewriting a large legacy system into a fresher technology typically fails, is because legacy code is full of "ifs" that once dealed with product-requests, edges-cases, rich-customers requests, etc. Without comments, many of those conditional blocks seem like the kind of code that should be axed on the new code. It's easier to put a comment like "BigCompany requested that all tickets older than December 4th 2019 to be prefixed with XYZ- because that's how their old system consumes them and they lost the code of their old systems, so they can't update them to use the newer tickets numbering scheme" vs trying to write variables and methods that provide the same intent.
      And simply all decades-old systems are full of code to support many non-obvious things that were covered by hundreds of devs over the years

    • @richardpaulhall
      @richardpaulhall Před rokem +2

      "Code comments seem almost useless on small projects or in small teams, where everyone can just intuit how code relates to the problem that the project is trying to solve."
      > I have not found that to be true. I worked on a multi-year project as one of the core programmers.
      Variable names were supposed to use Hungarian notation. Some devs did not follow that standard. Some devs did not rename the variable when the type of the variable was changed.
      Some devs, coming from a very old COBOL environment, set up global 'scratch' variables instead of declaring a local variable in a function.
      Some devs did not declare meaningful variable names.
      Some devs neither wrote clear code nor wrote comments.
      Many sections of the application required business knowledge. Devs with that knowledge -HAD- to include comments or their code would simply be impossible to support.
      Even tiny bits of code could be indecipherable if not well written.

  • @TonyHammitt
    @TonyHammitt Před rokem +11

    Other things I use comments for: Protocol descriptions for simulators, differences between functions with similar interfaces, validated development check code so it doesn't even get compiled, explicit listing of the usage and meaning of return values, checkpoints of where we are in the code relative to what is described in the documentation at the top. I'm the only one who typically reads my code, so I like to keep things understandable and keep my notes near where they're needed. I do like Knuth's recommendations, someone should be able to understand your implementation from the documentation and not have to spend a month trying to figure out why you did what you did. You really should write things down.

  • @user-xu7fb2ug4t
    @user-xu7fb2ug4t Před 9 měsíci

    Thanks bro, you just give me a new was to think before writing a code & document that.

  • @frenzywilliam3366
    @frenzywilliam3366 Před rokem

    Glad I found your channel, very good stuff, might patreon soon, I do want that macro optimization or what ever you called it.

  • @cookiemonster208
    @cookiemonster208 Před rokem +28

    Prior to watching I'm thinking, "what possible argument could he have for not writing comments!?"

    • @Parazeta
      @Parazeta Před rokem

      My take is usually: If your code needs comments, the code needs to be refactored in the first place or you are doing some complicated low level wizardry, that nobody besides you will understand with or without comments

  • @Spiderboydk
    @Spiderboydk Před rokem +7

    Comments are also great for documenting why a specific implementation was chosen and possibly which other approaches were tried and why they didn't work.

  • @MrLordFireDragon
    @MrLordFireDragon Před rokem +3

    I often write comments more like headings than explanations of code. Since most text editors format them differently, you can use this to easily jump to certain areas in your code by eye. You could extract out everything into functions or so on instead, but I find that forces me to scroll all over the place to find the function I want - if my code is a series of logical sequential steps, putting all the code back to back makes it easy to navigate intuitively.
    Other than that though, I do agree that you should preference writing easy to read and well documented code to comments.

  • @ivannuzhyn4668
    @ivannuzhyn4668 Před rokem

    Im not surprized that this channel has SO MANY subscribers after 2 month. Videos just awsome, please dont stop)))

  • @SufianBabri
    @SufianBabri Před rokem +3

    Excellent video. It basically ends the debate of two extremes: comment everything vs don't comment anything.
    I was aware of the 'comment everything' extreme, but with time I came to know that the other extreme was also bad (as I came to know use cases which you have also mentioned).

  • @travispulley5288
    @travispulley5288 Před rokem +19

    I add notes to myself about design choices sometimes to help with future refactoring and prevention of mistakes. I also litter my code with notes about technical debt (using TODO as a keyword), ideas, and ghost code that might be helpful. Fight me.
    Edit: I've also been paid to work with a team of other software engineers to look at bad code (from our own team, after the guy who wrote it left), collectively scratch our heads, and be the one to defy culture and suggest that more comments would be nice

  • @sparkoello2445
    @sparkoello2445 Před 8 měsíci

    In the section with big if - isnt it a bad thing in terms of performance to make new variable (bool in that example) - extra memory, time etc?

  • @augustoflach5090
    @augustoflach5090 Před 8 měsíci +1

    I like comments in code that new people tend to try to "fix", but are there for a reason. That line that fixes a bug but isn't very obvious and looks like shouldn't exist.
    Once I was woking on a file that had two css properties that my VSCode said that were actually the same. So I removed one. On the PR, an older guy said that the second property actually was processed differently for Safari, so removing it would break that part. And I was already the third person who tried to remove it bc of VSCode. These places claim for a comment, even if it just says "there is a reason for this line" or something like that

  • @yavvivvay
    @yavvivvay Před rokem +8

    I like giving examples to complex regexp (It is WAY easier to read when you look at what's parsed). Also if the code does anything that has no obvious reason, there should be a comment telling you why it's done.

  • @joshpatton757
    @joshpatton757 Před rokem +138

    One of my professors many years ago said "A comment is an apology to the next programmer. If you need a comment, you should consider what you are apologizing for, and determine if first can you fix it. That isn't to say that you shouldn't ever comment, sometimes you will have something to apologize for."
    That advice has held true for me. Comments should be rare and meaningful, and only used if there is not a better option.

    • @hanspeterfake3130
      @hanspeterfake3130 Před 6 měsíci +7

      Comments like this are the reason why I read the CZcams comment section. I think this will stick with me, thank you and your professor! 🙏

    • @BigRiku95
      @BigRiku95 Před 6 měsíci +3

      Yeah this is pretty spot on. You can always tell which parts of the codebase had to be rushed to hit a deadline as it’s a sea of comments basically apologising for how rushed it is

    • @suntzu1409
      @suntzu1409 Před 5 měsíci +1

      You could assign any attribute to comments and use that to justify not writing comments

    • @joshpatton757
      @joshpatton757 Před 5 měsíci +2

      @@suntzu1409 That's... not what is being advised here. You may wish to reread, particularly the last sentence.

    • @vincent78433
      @vincent78433 Před 5 měsíci +1

      actually this but the next programmer is also me 💀

  • @joneclegg
    @joneclegg Před rokem

    100% This. Thank you for detailing so clearly something i've been trying to tell people forever.

  • @ekandrot
    @ekandrot Před 9 měsíci

    In your first example, checking user_is_admin first could bypass the need for it to do any of the other work in that if-statement. Except now that they are three lines breaking it out, the if can not short-circuit, so all of the work will be done, no matter what.
    I agree with the idea that code should be simple and self documenting. Moving all of that work into another function cleans up those lines nicely, so someone reading the lower code won't have to read those four lines before getting to the logic flow.

  • @kevinfischer4869
    @kevinfischer4869 Před rokem +134

    No no no! Bad idea! Just leave stinking comments! Comments are important for understanding programmers intentions, so if a certain piece of code doesn’t do what the comment says it should do, then you may have found your bug! Also never underestimate how obtuse your code actually is - you may believe you settled on great names and types, but when you return a month later, you may find not everything is as self-explanatory as you thought!

    • @KANJICODER
      @KANJICODER Před rokem +29

      This. HALF my bugs are where the comment is correct and code is wrong.
      Comments are also the "answers to riddles". When you hear the answer to a riddle you are like, "oh my god, that is so obvious." Comments are the same way. Even if the code is written clearly, why atrophe your brain when you could just read a comment, and then glance at the code to make sure they agree?

    • @hawks3109
      @hawks3109 Před rokem +1

      Na comments are like docs, they get out of date from the code and often are misleading to what the code is really doing. You should only comment contextual things that the code doesn't capture (such as TODOs, reasons for an unconventional approach, possible optimizations, edge cases not covered, etc.), but your code should be written in a way you can read it and get what's going on relatively easily. This can be done for the vast majority of the code written. Comments should only be used by those who are still learning how to write clean code, but tbh you should be mentored at that point.

    • @absurdworlds
      @absurdworlds Před rokem +3

      Commenting code is as much of a skill as writing readable code. You may believe that your comments are helpful and easy to read, but when you return a month later you may find that your comments are as obtuse as the surrounding code.
      So it isn't as easy as "never write comments" or "always write comments". You have to actually stop and think if you have anything to add that's not already expressed in the code.

    • @KANJICODER
      @KANJICODER Před 11 měsíci +2

      100% Most bugs I find are because the COMMENT is correct and the code is wrong. Comments are a useful redundancy.
      I'll go so far as saying that it is okay to comment something you think is obvious.
      Because it's damn near impossible to know what is going to be obvious in the future, so don't even waste time trying to decide if you should write the comment or not. By the time you are done "thinking about it" you could have already wrote the comment.
      Lately I've been experimenting with a code base where I document EVERY LINE. 100% of the code is documented.
      Very slow to code, but 8 months in and I haven't hit a line of code I couldn't easily "de-mystify".

  • @GammaSigma1234
    @GammaSigma1234 Před rokem +17

    Another reason I personally use comments is to quickly identify critical sections of code in a particularly long source file (I am a C programmer in the embedded world).

    • @PhilLesh69
      @PhilLesh69 Před 10 měsíci +2

      I have used comments like that to speed up eye scanning and identifying a specific section of code to find later, faster.
      Like
      // * * * * * THIS IS WHERE A VAR GETS MODIFIED BY X FUNCTION * * * *

    • @GammaSigma1234
      @GammaSigma1234 Před 10 měsíci

      @@PhilLesh69 yes, exactly.

  • @augustoflach5090
    @augustoflach5090 Před 8 měsíci

    When you really see a comment on a project with good code and few comments, you immediately read it, because it must have a reason.
    When there are too many comments, you just end up skipping all of them

  • @closetothee3785
    @closetothee3785 Před rokem +2

    Not only performance-related code but any code that may be confusing requires a comment. I once read an emotional comment: "If you don't put the statement below you would receive the nasty error at line X". That's a good one. Without that it would be hard to figure out the purpose of that statement.
    Another scenario I can think of is put the related ticket number as a comment. Although we can track code change through version control systems, but it's not so easy to find out code change made years ago from the version control repository.

  • @Zahlenteufel1
    @Zahlenteufel1 Před rokem +18

    This is all fine and dandy in a finished project where you had time to polish everything but during development comments are so insanely useful. How would I code without TODOs and function outlines? And for what reason should I remove the function outline afterwards? Maybe this is different depending on what you're working on but give comments some love, man!

    • @driden1987
      @driden1987 Před rokem +4

      +1 for TODOs or useful links in the code

    • @juliocezarsilva5979
      @juliocezarsilva5979 Před rokem +1

      It's clear to me he's not talking about those here.

    • @corvus8638
      @corvus8638 Před rokem +2

      @@juliocezarsilva5979 He shouldn’t have titled the video don’t make comments then

    • @climatechangedoesntbargain9140
      @climatechangedoesntbargain9140 Před rokem

      What is a function outline?
      Todos I understand

    • @Zahlenteufel1
      @Zahlenteufel1 Před rokem

      @@climatechangedoesntbargain9140 when I need to write a function, I start by outlining the steps in comments. Then I "explode" those by either adding more comments explaining the sub-steps, creating a helper-function or just adding the code necessary to do that step. Then I leave the comments in, as they double as "headings" for the sections.
      E.g.
      /* save event to database */
      event_string = event.to_string()
      config = getDbConfig(...)
      pushToDb(config, event_string)
      /* next section */

  • @douglasdbs7139
    @douglasdbs7139 Před rokem +296

    Please, *DO COMMENT* your codes unless you have been oriented not to do so. Part of my job is to analyze other people's code every day, and although I can perfectly figure out what the code is doing, if the author includes comments presenting code and telling what the code is supposed to do makes the whole code debugging process faster. It is faster and easier to let the coder guide me through the code through his/her key comments and then double checking what the code is actually doing than having to figure out the code from zero. If you disagree, I encourage you to do the following experiment by yourself: review say, 50 pieces of code from random github repos without comments, then do the same for 50 pieces of code with comments. Do that a few times and you start missing the commented codes. I have seen this trend recently of "do not comment your code" and could not disagree more. I think it comes mainly from a very narrow view of the purpose of coding, which is that every code is supposed to be a product and to be handled/used by mid to experienced programmers. This cannot be more distant from the real world. Many people write tutorial codes for teaching, comments only add value to the tutorial. People write codes for automating repetitive tasks they do, people write codes to solve mathematical formulas that are too hard to do by hand, people write codes for researching and for the sake of scientific discovery, people write codes for fun! In none of these examples commenting is harmful, on the contrary. Even in a more "professional" setting, in most contractor/ consulting jobs for algorithm development, chances are that the company hiring you wants your code to be thoroughly commented so they know your thought process and how you solved that specific problem you were hired to solve, if they can avoid having to go figure out the code from scratch, they will prefer so (imagine your code will be seen by more people than just the developers). If they want, they will remove your comments afterwards. I can give examples of situations where comments are welcome for hours. In addition to all these points, there are some fallacies in all this "do not comment your codes" that should be addressed.
    The fallacy that "codes should be self-evident so comments are not necessary"
    First, this nonsense of "good code is self-evident thus comments are not necessary". Well, electrical circuits are also self-evident from the connections and components (an experienced engineer can in general figure out what the circuit is doing by looking at the connections and components), but almost every circuit datasheet is commented and circuit boards are often printed with the name of components and other symbols indicating what that given region of board is doing. A mathematical solution or set of equations are also self evident from the expressions themselves (an experienced mathematician could figure out what the math is doing by only looking at the formulas), but almost always math texts are commented and the symbols and notation are explained in text. Sheet music are also supposed to be self-evident (formally trained musicians can figure out how to play the song by only looking at the sheets), but sheet music are often commented as well, with parts explicit highlighting changes in tempo and other features, as well as emphasizing the meaning of the symbols used in the sheet. Essays are also supposed to be self-evident (you can read the essay and figure out what is the meaning and purpose of what is written), but it is good practice in every essay to start the first paragraph offering a context or giving an overview of what will be presented in the next paragraphs. Electrical circuits, mathematical expressions/demonstrations, music sheets and written essays are all ways of communicating a list of instructions to a given person or system, or ways to convey information, so as coding. In all of these examples (and I can think of many others), commenting is seen as a good practice regardless of the quality of built circuit/math expressions/sheet music/essay, why would commenting in coding be different?
    The fallacy that "programmers should know how to figure out the code"
    Yes, ideally programmers should know how to figure out what the code is doing. This fallacy starts from the standpoint that all programmers should be (or even worse, are) skilled enough or that they would have the time to understand well the codes they are using. This is a totally arrogant viewpoint and again could not be more distant from the real world. I know that I can read a Python code perhaps much faster than the average, but it does not mean that everyone is at the same level as me. It means that I had a lot of opportunities in life and enough time to learn coding to a level where I can do that today. But this is not the case for everyone. Everyday thousands of new programmers start the coding journey and they are not expected to be at the level of understanding a given code in front of them without any support. Not commenting codes would just leave out a big portion of potential future great coders. Also, the vast majority of the algorithms out there are likely not good, and most likely if you write an algorithm thinking that it is well-written and self-evident, chances are that your code is not that good. If in the real world codes are ugly, coders are often beginners, conding applications are diverse, resources for training mid to expert coders are scarce, why insist on not commenting the codes? Imagine again if mathematicians decided that "all math should be self-evident, let's abolish comments in math texts", would that be beneficial or against the development of mathematics? If electrical/electronics engineers decided that "circuits should be self-evident, let's abolish visual cues printed on the circuit board", would that be beneficial or against the development of electronics? Why would that be different in coding?
    The fallacy that "in big company X, they are oriented to not comment their codes"
    We all have heard that Google software developers don't comment their codes, and that is true to other big techs too. Therefore "you should not comment your code" because the big shots in software development don't do that. That's again a very biased viewpoint, you are taking as example the "creme de la creme" of the software development industry, the state of the art, as reference on how to behave in the real world. Initially it might sound as a good idea to mimic what those big shots are doing, but in the "real world", for the vast majority of the applications where coding is necessary, it doesn't make sense. Again, I am sure that i) the electrical engineers from the classical Bell labs, or from the Analog Devices did not need any support to analyze their electrical circuits by heart, that ii) the students of the Lucasian Professor of Mathematics in Cambridge, or people researching String Theory don't need to read the between line codes to understand math demonstrations, or iii) that musicians Philharmonic Orchestra of San Francisco or students of the Berklee College of Music can read sheet music without without any supporting coding glossary or comments, but nobody would use as argument i), ii), and iii) to not use supporting comments or glossary in circuits/mathematical demonstration/sheet music. They are world elite athetlets in their respective areas, but it does not mean that rest of the world should do or can do the same.

    • @phoebebaker1575
      @phoebebaker1575 Před rokem +18

      This could be a poem! Or a short short story. Eloquent. I like your example of offering the experiment of 50 pieces of code, commented and uncommented. If we go to the other extreme, and say “The more comments, the better!” does there become a point where it is clear too much is too much? What does that look like?

    • @wrawler
      @wrawler Před rokem +2

      oh man!!!

    • @landonmackey1091
      @landonmackey1091 Před rokem +36

      You are completely correct and there is pretty much no valid counterargument. Nobody can read minds, nobody can remember why they implemented a roundabout solution instead of the obvious one, nobody can accurately predict what a function returns given every possible argument, etc. etc. ad infinitum. The issue that those advocating comment-less code don’t realize is that they actually want a lesser solution to a solved problem: clear comprehension of the code. If a section of code is missing an element for someone to comprehend it and a single-line comment can fulfill that element, why restructure your code to avoid losing that single line?

    • @douglasdbs7139
      @douglasdbs7139 Před rokem +15

      @@landonmackey1091 thanks Landon, this whole "don't comment your code" thing has been bothering me for a while now. It's good to know that there are more coders out there that believe this is nonsense too.

    • @CFEF44AB1399978B0011
      @CFEF44AB1399978B0011 Před rokem +25

      I work at Google as a swe, and people absolutely comment their code. They just do so with care. Simple comments that explain a method, complex condition, or link out to a design. People don’t comment every line, but our code reviews typically are very strict on naming things, and all of the other points. But this idea that big tech doesn’t comment their code is hogwash. Also, a lot of big tech coding is writing Java boilerplate. a lot of our commenting the boilerplate comes in system and subsystem level designs. These designs are extremely important for onboarding newbys but still there ends up being a gulf between system level documentation and the real world implementation, and none of these code channels ever cover the importance of directory or package level structure organization and naming. They also never cover the importance of designing sensible patterns for how components across a massive codebbase interconnect. I’ve seen some truely apoling messes caused by inconsistant standards around how a team documents and actually implements the interconnect between components and subsystems, causing engineers to bubblegum things together in very strange ways. Immagine your FruitFlyEnclosureController has part of a FruitFlyDoorActuator embeded in it rather than your fruitFlyEnclosureController talking to the FruitFlyDoorActuator using a protocol that the team can understand? You can document it with english or an interface, but likely your interface will be a defacto form of comments because a ActuatorCommunication is a form of documentation or commen’t because it will be simpler than english, but not as complex as code and to refactor the code requires either refactoring the interface or keeping the communication compatable, thus maintaining the coupling. I agree with op but I’d add that big tech may seem like we don’t comment code, but there are a lot of comments in specific places where things get tricky, or outside codebases in designs. And You can't become lazy with design to avoid comments, because code is only a relatively small part of our jobs.

  • @arranschlosberg7434
    @arranschlosberg7434 Před 11 měsíci

    The litmus test I've taught for comments is to explain why, but never how nor what. You can't capture a "why" in code and the need to comment the other two suggests refactoring as you suggest.
    I love your channel btw and will definitely link to your videos in code reviews!

  • @ThaitopYT
    @ThaitopYT Před 8 měsíci

    I agreed.
    Many people don't realise that comments need maintenance too.
    You can't just write once and forget or update whenever you feel like.
    It's a liable task so you should keep it minimum.

  • @fidget2030
    @fidget2030 Před rokem +90

    This is the first time I actually disagree with one of your videos. It is easy to quickly interpret your own code if you have properly chosen variable names etc. But this is not always the case for code written by others. Comments are not there solely for yourself, but to aid others who might work on your code. The risk of comments becoming out of sync with the code they describe is real, but it seems just a factor in good coding to update comments when you do edit the code. Those few extra seconds now will save a future individual a lot more time than that. Writing completely comment-free code assumes everyone to have your level of fluency in reading code, and that they will approach problems the same way.

    • @beclops
      @beclops Před rokem +37

      Yeah, it seems to me arguing against comments is like arguing against a table of contents in a book because “the inside of the book already describes what it’s saying”

    • @bernhardkrickl5197
      @bernhardkrickl5197 Před rokem +4

      Sometimes when I feel the need to write a comment, I just write it, take a step back and look at it to see what it is saying that the code isn't. Then I think again how to change the code so that I don't need the comment. After all, a comment might be equally unclear to somebody else as the code is. However, I also see some good reasons for comments and write them if necessary.

    • @beclops
      @beclops Před rokem +2

      @@bernhardkrickl5197 I like this approach, there’s definitely a point where comments aren’t meaningful which I think is what self documenting code aims to fix, but people tend to over correct and say “never comment”

    • @sdjhgfkshfswdfhskljh3360
      @sdjhgfkshfswdfhskljh3360 Před rokem

      @@beclops and now think what is the size of contents comparing to the whole book. 1% of comments describing high-level things is not a bad thing.

    • @beclops
      @beclops Před rokem +1

      @@sdjhgfkshfswdfhskljh3360 Yes haha. And when it gets to the point where you start having an equal amount of both or anywhere close, you know you have a problem

  • @Freebytes
    @Freebytes Před rokem +3

    Excellent video as always. One thing you missed is that comments should be supplied for attribution. That is, the source and author if you copy code from other places. The link can be followed to determine why the code was implemented in a specific way, and you should always give credit.

  • @cooperriehl944
    @cooperriehl944 Před 11 měsíci

    +1 to all your points, especially the value of documentation comments as well as specific cases where inline comments make sense. I agree that code should be self-documenting as much as possible. When I code, I often lay out the architecture with high-level comments, then translate those comments into sensible function names and/or operations, THEN go implement the actual functions. Any comments that I can't easily translate into code are worth a second glance, as they may be indicators that the architecture is too complex and needs to be refactored.
    If I'm looking through an unfamiliar piece of code, I will read inline comments to help me get a high-level understanding of what the code does. I rarely trust anything more detailed than a general overview, though. Especially if a comment lists specific pieces of data like numbers, variable names, etc. I will read the code surrounding it to verify that the comment isn't out-of-date.

  • @ducnhatphung
    @ducnhatphung Před 8 měsíci

    As a developer, I used to have the same thinking that code is the single source of truth and everything have to be expressed simply in code. That until I have to read and refactor other one's code. The code base is so huge that you cannot get the whole picture by just simply reading the code. What I have to do is to comment every single ideas I come across when I read the code so that when I re-read it, I can capture the ideas with the glance of an eye. The same thing happen when you re-write the code. If your idea is so huge, you cannot just simply write the code and keep everything in your head. You will start forgetting things in one place or another. Code documentation just not work because it is the high level documentation, it is not mapped with your code when you are writing. So what I do is to write down TODO comments first before adding any line of code so that when I come back, I can continue what I have left without remembering too much.
    Since then, I keep the habit of writing code comments. It is not only because of code refactoring, it is to tell other ones know what you are going to do before let's them dig deeper into your code to see whether it is correct or whether they have to change something.
    Code is not simply adding functions and naming variables, there are many problems that you come across when you write code. Sometimes, one line of code does not solve the problem, you may need to add two lines, three lines or multiple lines of code just to express one simply idea. In the end, code is not something easy to read regardless of the programming language you use or how you name your functions. Adding comments may help you clear your mind, save your time on naming and help other ones better understand your code.

  • @Morses23
    @Morses23 Před rokem +5

    One more category of exceptions I would add are comments used to explain WHY short but complex sections of code were made. Usually functions solve it by it's name. But when it's only few lines of code, solution with function would look like some of the really controversial recommendations from Clean Code by Robert Martin.
    More recently, I was surprised that even though the size of a C++ vector is represented by the size_t, the theoretical limit on the size of a vector is the maximum value of the ssize_t type. And, in practice, it is even smaller. Therefore, a comment referencing the documentation for the vector::max_size() and std::advance() functions can explain WHY the size_t index is converted to ssize_t when working with vector iterators.

  • @Semellie
    @Semellie Před rokem +6

    The problem with just rewriting the code to make comments not necessary is that that is not always possible. I worked extensively with legacy code bases in the past where we had neither time nor money to do extensive refactoring. I was glad for any comment in there, and would always write my own on stuff i touched because the system was too complex. Of course, that's not the norm, and in general, having code that is easy to understand is preferable.

  • @lstuma
    @lstuma Před rokem +17

    I feel like this is fine in a lot of cases but sometimes code can seriously look gibberish and in those cases i think comments are an absolute necessity. Since most stuff gets optimized away anyway though, it is definitely a good idea to use more descriptive code!

    • @ninobach7456
      @ninobach7456 Před 9 měsíci

      Gotta have good variable names. Though I find it incredibly hard to name variables

    • @elirantuil5003
      @elirantuil5003 Před 9 měsíci +1

      ​@@ninobach7456thats a feature, it helps you define exactly what the role of the variable and for me, more than once I found out my "plan of attack" is flawed or that I don't need a variable while trying to name one.

    • @Peter_1986
      @Peter_1986 Před 7 měsíci

      I like to use the "#define" directive as a convenient way to rename long and awkward lines into something that is plain English.

  • @Ciph3rzer0
    @Ciph3rzer0 Před 11 měsíci

    Agree, I find almost every function I write now is perfectly and neatly explained by the code as written. And I document the function to explain how it relates to everything else as a black box.