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.
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
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..
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 ;-)
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.
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.
@@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.
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
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
@@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.
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.
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.
@@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.
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.
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'
"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!
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. :(
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.
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
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).
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?
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.
@@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.
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.
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.
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
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.
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.
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
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.
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.
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...
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.
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.
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 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.
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.
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.
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.
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.
The problem with these videos is I think they address different points than what we experience. The video is to reduce redundant and fractured comments and tries to create a "blanket" rule. The rule has caveats like at the end, but ignores a lot of other use cases where it makes sense. Coders will watch the video and then go too far with it. Reminds me of every other programming fad. We're all human at the end and what works best for any one person, team, or company may not work well for others and we need to rely on our judgment.
Assembly code is one of the few places where comments are really necessary but if you're using something more abstract - basically any programming language - they are much less necessary.
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.
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.
@@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.
@@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.
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?
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.
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.
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
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
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.
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 :(
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.
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.
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 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.
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.
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.
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.
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
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 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
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.
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
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".
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.
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.
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.
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.
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
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.
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"
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...
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!
I'm the other way around. I write all the code, then add comments. And so far I've only ever done small projects for fun, so these comments end up being useless because I never need look at the code again.
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!
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.
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
@@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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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)
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.
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.
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 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)
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.
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.
@@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.
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!
@@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.
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.
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.
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?
@@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.
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.
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.
Thanks for the video. I was tempted to comment on some of the things you address towards the end of the video. I think my only problem is the title of the video: "Don't Write Comments". Many (specially less experienced programmers) will take that, and stop there. Use it as an excuse to NOT write documentation (i.e. the why of code, and not the how or what; that last part, I wholly agree, is better left to the code itself).
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.
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
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:)
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.
@@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.
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.
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.
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.
i watched this video months ago and was like 'no way comments are way better'. but ever since ive started writing less comments and more readable code. improved my coding dramatically. thank you so much code aesthetic!
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.
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.
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.
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.
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.
@@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.
"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.
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.
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
"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.
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.
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.
"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.
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.
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).
@@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.
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!
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?
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.
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.
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".
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
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
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.
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.
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
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
Git commits should have comments. I agree with the video's take on when comments are actually needed in code and how to avoid them. I like source code logs with comments to find out how a project to be the way it is, and going forward make sure that commits line up with what the dev thinks they do.
about a year ago, I was more of a newbie programmer (I've been making a pretty complex game) and my coding practices were still "fresh" from college. I commented like a mofo, every other line. I watched this video and though it was a dumb. Over the last year of programming, I've come to realize this video is correct. I barely comment my code anymore outside of special circumstances, and meticulously make sure every method and variable name is perfectly descriptive, using the hell out of VS' rename feature. What happened was, I started coming across comments that were flat out wrong, out of date, etc or just made no sense to me. It started looking like clutter to me and i wasn't even reading them. So yeah, I found out the hard way this guy is right. I still like comments in front of methods, and visual studio actually provides a nice thing so you can label them in intellisense doing that, as well as code blocks in methods. There's also complex stuff you just can't get around and need comments for, such as explaining WHY you chose a way of doing things that might be whacky (so you don't change it back)
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.
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
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.
@@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.
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.
This video is concise and has a point. However, if you are a beginner, you need to comment. Comment, and comment lots! If you're a beginner, you're probably just writing code to study, you're not collaborating in other projects. If it's your code and only yours, honestly, coment loads. Make your code your doc playground. This will help you remember things.
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.
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).
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 * * * *
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.
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.
@@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.
@@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.
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.
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”
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.
@@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 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
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!
You said yourself. Keep your specification as close to your code as possible. That's why I use comments for the specification itself. I don't need any extra tool to generate a seperate document, and can directly compare if my specification and code match.
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.
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.
In addition to it, modern IDEs like JetBrains ones can provide comment check when you refactoring the variables. This may help you do lots of dirties if you have to write a comment.
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
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!
@@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 */
As a CS Student, this makes sense to me and is a little different from the advice we’re given. However, two very good reasons for commenting in my context: (1) Not all students stick to (or even know) good code aesthetic conventions, and commenting helps other group members and teachers figure out what’s going on. Once we’re all graduated I expect the standard for that changes. (2) so profs can explain assignments within the code files themselves/so we can demarcate questions or different sections of assignments for their benefit.
1) not all students write comments either - if you instruct them to comment, you could as well instruct them to write readable code 2) often it is possible to formulate assignments as tests; you can demarcate different sections of the assignments with functions, no?
@@climatechangedoesntbargain9140 yeah fair enough - I guess I'm just used to the way we're taught. They totally could just teach us to write self-descriptive code in the first place. I think comments still have their uses, but then I don't think anyone ever said they don't. You make good points, sir.
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.
I personally write comments above the headers of whatever im writing, be it a class or a function. I briefly explain what it does, what the parameters do, what it returns, what exceptions it could throw and perhaps some miscellaneous information such as frameworks used etc. Always think about what other people would think when seeing your code for the first time! It might be self explanatory to you, but certainly not to another developer and even if, the time you save people from not having to interpret your code but instead just reading the description you gave it is almost always worth the extra effort. Every software developer will be very thankful for it.
@@gabrielaudette4591 not at all. Theres several plugins and extensions that make it a benefit to write your documentation into your code. For example with javadocs, you have the benefit of having it right in front of you immediately and also have it attached if you hover over the function or class. All while automatically generating html pages for you to use as official documentation.
@@darkpit3124 "Javadocs in Nonpublic Code As useful as javadocs are for public APIs, they are anathema to code that is not intended for public consumption. Generating javadoc pages for the classes and functions inside a system is not generally useful, and the extra formality of the javadoc comments amounts to little more than cruft and distraction." Clean code p.71
Comments are often needed for edge cases; not to explain how it works but why the code is even there to begin with. For example, you use some library that freaks out on CRLF line endings. While converting line endings may be totally clear in how it works, it may be very confusing why it happens at some point.
i often find it easier to read an english sentence thats all in a unique text color than to read an if statement, even if that statement is structured in some of the ways shown in this vid. maybe thats just me. code tends to blend together to me, but if its broken up by comments that explain whats happening step by step, i find it much easier to read. also comments can also provide a brief description that simply structuring the condition of an if/while/etc cant provide (especially for loops). something like "iterate through this list of numbers on each item in this queue on a first-in-first-out basis" is much easier than reading through an entire while loop with 20+ lines of code inside including a nested for loop. this way i can just label that entire while loop with what its purpose is
@@JonathanTrevatt Documentation should describe the intended function. I think you missed the latter portion of the video that makes a distinction between comments and documentation.
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!
My main use for comments is making #TODOs for later optimization/refactoring or #FIXMEs for things that are out of scope for fixing right now. Since these comments are adjacent to the culprit, they rarely go out of date or "lie". They also communicate non-obvious issues to other developers, so if something is known to be suboptimal or failing then they don't have to waste time re-diagnosing the issue.
"if you write code clearly enough with well-thought out naming and structure, other people will understand it" is a delightful bit of optimism at the most diplomatic and an indication of one's position on the spectrum at the least. Doc systems for functions are excellent and should be the first line of documenting code because they also feed IDEs which do code hinting, but in real world conditions we will write code that LOOKS like an inefficient way of doing something because we've discovered flaws, even bugs in native methods that seem like a better way and we must remind ourselves never mind others not to go back and "fix" that line later. Comments shouldn't be a substitute for writing clear code but beyond that, this is like style checkers that complain about lines going over 80 characters: it doesn't matter to performance and we should mind our own business about it.
Would be pretty cool if comments were the tests. 1. You comment some code in a specific way that is readable by humans but also executable by the test runner 2. Your test runner executes the given piece of code and checks whether the comment describes it accurately 3. As a bonus you could also implement visualizations that an IDE would render like graphs or output values given various input sliders
I think for me, the biggest example of necessary code comments is the triple slash style comments that IDEs use. While I'm sure everyone would just say "Oh just look at the documentation, it's the same thing." In context, it's a lot nicer to look at the IDE description and format that you're used to, as well as see all the pieces of the code correctly syntax highlighted because of it. I also think that when working on smaller but semi-complex projects, having comments for others to help clean up your code or to return to your own code is great, and can make a good pair *with* good documentation. They should not be mutually exclusive in my opinion.
/// and /** */ are actually the same syntax that docygen uses. So you can easily write the ide description and then run doxygen to generate a nice(ish) html for your project that documents all the functions and variables
Frankly, this really depends on the language. In some languages you can _encode_ basically everything. In others, it may be basically impossible in many cases. The former ones are languages that include full proof checking systems, which (unfortunately) makes them pretty unwieldy in many cases. Thankfully there are a lot of languages in-between. (Mostly these with expressive types.)
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.
Finally someone gets me
Just a typical stackoverflow error fix code
That's how I do it
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
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..
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 ;-)
This! 🙌🏽
I was gonna write this myself :)
I've always followed the "not what but why" rule. You hit it on the head.
Agreed
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.
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.
@@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.
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
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
@@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.
You forget "why" the code works :D
Okay, that's cool and all, but writing assembly without comments is suicidal.
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.
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.
@@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.
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.
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'
@@elirantuil5003Better for you. Not for anyone else who wants to read your minimal code.
"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!
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. :(
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.
@@BorderKeeper Bad code requires comments. Clean code does not. Point taken.
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
Wtf I'm stoned reading this and the quote got perfectly synced with the vid
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).
Exactly. Only simple code need no comments
And sometimes it is just not possible to express convoluted business logic with non-convoluted code
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?
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.
@@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.
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.
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.
Comments lie.
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
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.
Me too. I regularly thank past me for anticipating and addressing the issues which then-future me would be likely to not understand.
I like to explain to future me what now me was trying to achieve.
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.
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
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.
@@RobBCactiveI write functions for pretty much anything I wanna use more than once. Everything else goes under a header
@@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?
@@silvercakes Most IDE programs allow you to test units like that without needing to make it into a function sometimes.
@@SimonWoodburyForgetIt is probably the main real use of comments 😂😂😂
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.
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.
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.
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...
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.
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.
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.
This means that your code isn’t self explanatory and of bad quality 🤷♂️
That should be the documentation
@@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.
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.
@@ImperiumLibertas My brother in Christ, just reading the initialization of a SINGLE Vulkan API object will usually take you more than five seconds.
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.
This needs pinned right before this video is taken down.
I mean I respect it, but don't do that
Bruh
oh my god
thats... bad
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.
Why is the function so large? break it up and give the methods good names.
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.
Did the first 2 replies even read the second half of the comment...?
@@kingacrisius Exactly. The OP literally anticipated these kinds of replies and preempted them, only for his good efforts to be wasted.
The problem with these videos is I think they address different points than what we experience. The video is to reduce redundant and fractured comments and tries to create a "blanket" rule. The rule has caveats like at the end, but ignores a lot of other use cases where it makes sense. Coders will watch the video and then go too far with it. Reminds me of every other programming fad. We're all human at the end and what works best for any one person, team, or company may not work well for others and we need to rely on our judgment.
Good luck maintaining a 400 line assembly file with no comments.
Assembly code is one of the few places where comments are really necessary but if you're using something more abstract - basically any programming language - they are much less necessary.
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.
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.
@@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.
@@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.
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?
dude don't write comments like he just said
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.
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.
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
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
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.
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 :(
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.
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.
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.
@@danielcommins1285 He did explicitly point out that performance optimisations warrant a comment.
@@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.
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.
There is something very satisfying about picking descriptive variable names, so that the variables themselves serve as "comments".
I like this approach: the code should tell you what it does, the comments should tell you why it's doing that.
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.
Which is said in the video (specific things for optimisation or obscure algorithms should have comments)
@@MagicGonads I mean specifically the video author discusses obscure mathematical algorithms, not "hacky black magic"
@@Sancarn both are examples of "hacky black magic" (from the perspective of reading the code)
Yes but the rule is don't write comment, there will be exceptions to the rule.
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.
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.
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
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
@@ElektrykFlaaj Relying on tests to document function of an app is insane.
@@0oShwavyo0 if you are adding comments explains types in a dynamic language, you are doing dynamic languages wrong
@@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
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.
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
It’s just a clickbait title to get more views
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".
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.
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.
ABSOTELUTELY FUCKING NOT!
@@mp_petrovYou're not with your friends having a beer, behave yourself.
@@GreyDeathVaccine 🫡
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.
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.
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
Me too. It helps me with debugging as well.
You might try finding a way to make your code read more like your prose.
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.
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"
Thanks for replies. I'll see what I can do
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...
7. "This shouldn't work, but it does. Don't touch it"
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!
I'm the other way around. I write all the code, then add comments. And so far I've only ever done small projects for fun, so these comments end up being useless because I never need look at the code again.
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!
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.
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
@@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.
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.
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.
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.
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.
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.
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.
I find that people who write unreadable code also write unhelpful comments, like /* check if status is 4 and set sent flag */
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
"Comments can lie, code can not" this dude got the best quotes about coding honestly
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.
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.
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.
That is pretty much a description for literate programming
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)
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.
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.
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.
also wouldnt adding more variables and stuff to make code "cleaner" like that take up more memory?
@@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)
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.
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.
@@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.
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!
Gotta have good variable names. Though I find it incredibly hard to name variables
@@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.
I like to use the "#define" directive as a convenient way to rename long and awkward lines into something that is plain English.
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.
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.
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?
@@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.
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.
esp if something is deliberately built to break or edge case not to be fixed like this.
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.
I vibe with this
Thanks for the video. I was tempted to comment on some of the things you address towards the end of the video.
I think my only problem is the title of the video: "Don't Write Comments". Many (specially less experienced programmers) will take that, and stop there. Use it as an excuse to NOT write documentation (i.e. the why of code, and not the how or what; that last part, I wholly agree, is better left to the code itself).
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.
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
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:)
I've had applicants that take self documenting code a little too seriously and didn't add comments to function declarations. Please do both.
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.
@@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.
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.
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.
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.
i watched this video months ago and was like 'no way comments are way better'. but ever since ive started writing less comments and more readable code. improved my coding dramatically. thank you so much code aesthetic!
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.
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.
Do you mean "literate programming" introduced in 1984 by Donald Knuth?
@@patrickcorliss8878 Yeah I think my autocorrect got me. :-)
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.
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.
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.
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.
@@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.
"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.
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.
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
"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.
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.
Still waiting for that Dependency Injection video! You do great matterial!
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.
"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.
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.
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).
@@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."
@@Tynach Well kinda yes, kinda no, because it becomes more like structural hints than actual code comments.
@@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.
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!
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?
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.
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.
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".
Yep. And codd documentation is exactly what I don't read.
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
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
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.
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.
Comments like this are the reason why I read the RUclips comment section. I think this will stick with me, thank you and your professor! 🙏
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
You could assign any attribute to comments and use that to justify not writing comments
@@suntzu1409 That's... not what is being advised here. You may wish to reread, particularly the last sentence.
actually this but the next programmer is also me 💀
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
Git commits should have comments. I agree with the video's take on when comments are actually needed in code and how to avoid them. I like source code logs with comments to find out how a project to be the way it is, and going forward make sure that commits line up with what the dev thinks they do.
about a year ago, I was more of a newbie programmer (I've been making a pretty complex game) and my coding practices were still "fresh" from college. I commented like a mofo, every other line. I watched this video and though it was a dumb. Over the last year of programming, I've come to realize this video is correct. I barely comment my code anymore outside of special circumstances, and meticulously make sure every method and variable name is perfectly descriptive, using the hell out of VS' rename feature. What happened was, I started coming across comments that were flat out wrong, out of date, etc or just made no sense to me. It started looking like clutter to me and i wasn't even reading them. So yeah, I found out the hard way this guy is right. I still like comments in front of methods, and visual studio actually provides a nice thing so you can label them in intellisense doing that, as well as code blocks in methods. There's also complex stuff you just can't get around and need comments for, such as explaining WHY you chose a way of doing things that might be whacky (so you don't change it back)
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.
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
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.
@@donjindra...or save her some time.
@@reindeerdashie Obviously. But I don't pander to new language sensibilities.
@@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.
@@donjindra yeah, no, this is horseshit. Your response, I mean - not the reasonable adjustment proposed by @reindeerdashie .
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.
This video is concise and has a point. However, if you are a beginner, you need to comment. Comment, and comment lots! If you're a beginner, you're probably just writing code to study, you're not collaborating in other projects. If it's your code and only yours, honestly, coment loads. Make your code your doc playground. This will help you remember things.
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.
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).
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 * * * *
@@PhilLesh69 yes, exactly.
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.
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.
@@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.
@@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.
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.
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”
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.
@@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”
@@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.
@@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
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!
You said yourself. Keep your specification as close to your code as possible. That's why I use comments for the specification itself. I don't need any extra tool to generate a seperate document, and can directly compare if my specification and code match.
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.
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.
In addition to it, modern IDEs like JetBrains ones can provide comment check when you refactoring the variables. This may help you do lots of dirties if you have to write a comment.
Management: Do you write documentation?
Me: Does self documenting code count?
Management: Yes
Me: Then no
3:44 “The world needs more high quality documentation.” Preach, brother!
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
This doesn't happen if you check the condition (ideally with an early return/continue) before defining the next variable.
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!
+1 for TODOs or useful links in the code
It's clear to me he's not talking about those here.
@@juliocezarsilva5979 He shouldn’t have titled the video don’t make comments then
What is a function outline?
Todos I understand
@@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 */
As a CS Student, this makes sense to me and is a little different from the advice we’re given. However, two very good reasons for commenting in my context: (1) Not all students stick to (or even know) good code aesthetic conventions, and commenting helps other group members and teachers figure out what’s going on. Once we’re all graduated I expect the standard for that changes. (2) so profs can explain assignments within the code files themselves/so we can demarcate questions or different sections of assignments for their benefit.
1) not all students write comments either - if you instruct them to comment, you could as well instruct them to write readable code
2) often it is possible to formulate assignments as tests; you can demarcate different sections of the assignments with functions, no?
@@climatechangedoesntbargain9140 yeah fair enough - I guess I'm just used to the way we're taught. They totally could just teach us to write self-descriptive code in the first place. I think comments still have their uses, but then I don't think anyone ever said they don't. You make good points, sir.
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.
As someone learning development, comments have been really helpful in retaining what things do.
I personally write comments above the headers of whatever im writing, be it a class or a function.
I briefly explain what it does, what the parameters do, what it returns, what exceptions it could throw and perhaps some miscellaneous information such as frameworks used etc.
Always think about what other people would think when seeing your code for the first time! It might be self explanatory to you, but certainly not to another developer and even if, the time you save people from not having to interpret your code but instead just reading the description you gave it is almost always worth the extra effort.
Every software developer will be very thankful for it.
still, separate documentation is just better for those cases. IMO you just add noise to your code.
@@gabrielaudette4591 not at all. Theres several plugins and extensions that make it a benefit to write your documentation into your code.
For example with javadocs, you have the benefit of having it right in front of you immediately and also have it attached if you hover over the function or class.
All while automatically generating html pages for you to use as official documentation.
@@darkpit3124 "Javadocs in Nonpublic Code
As useful as javadocs are for public APIs, they are anathema to code that is not intended
for public consumption. Generating javadoc pages for the classes and functions inside a
system is not generally useful, and the extra formality of the javadoc comments amounts
to little more than cruft and distraction." Clean code p.71
Comments are often needed for edge cases; not to explain how it works but why the code is even there to begin with. For example, you use some library that freaks out on CRLF line endings. While converting line endings may be totally clear in how it works, it may be very confusing why it happens at some point.
i often find it easier to read an english sentence thats all in a unique text color than to read an if statement, even if that statement is structured in some of the ways shown in this vid. maybe thats just me. code tends to blend together to me, but if its broken up by comments that explain whats happening step by step, i find it much easier to read.
also comments can also provide a brief description that simply structuring the condition of an if/while/etc cant provide (especially for loops). something like "iterate through this list of numbers on each item in this queue on a first-in-first-out basis" is much easier than reading through an entire while loop with 20+ lines of code inside including a nested for loop. this way i can just label that entire while loop with what its purpose is
After more practice you'll read code as easy as english. Either this is a lack of experience or poorly written code.
@@JonathanTrevatt Documentation should describe the intended function. I think you missed the latter portion of the video that makes a distinction between comments and documentation.
I like writing comments, it is useful when one has to refactor old and forgotten code.
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!
This is taking controversial in coding to a whole other level.
What about when I need to add something like
// I'm sorry I made this, this is horrible, you should not write code like this
//Yes this is a memory leak. Too bad!
My main use for comments is making #TODOs for later optimization/refactoring or #FIXMEs for things that are out of scope for fixing right now. Since these comments are adjacent to the culprit, they rarely go out of date or "lie". They also communicate non-obvious issues to other developers, so if something is known to be suboptimal or failing then they don't have to waste time re-diagnosing the issue.
Your only problem is that nobody ever looks at the TODO's and FIXME's again. Much better to raise a ticket if you have an issue tracking system,.
100% This. Thank you for detailing so clearly something i've been trying to tell people forever.
"if you write code clearly enough with well-thought out naming and structure, other people will understand it" is a delightful bit of optimism at the most diplomatic and an indication of one's position on the spectrum at the least.
Doc systems for functions are excellent and should be the first line of documenting code because they also feed IDEs which do code hinting, but in real world conditions we will write code that LOOKS like an inefficient way of doing something because we've discovered flaws, even bugs in native methods that seem like a better way and we must remind ourselves never mind others not to go back and "fix" that line later.
Comments shouldn't be a substitute for writing clear code but beyond that, this is like style checkers that complain about lines going over 80 characters: it doesn't matter to performance and we should mind our own business about it.
Would be pretty cool if comments were the tests.
1. You comment some code in a specific way that is readable by humans but also executable by the test runner
2. Your test runner executes the given piece of code and checks whether the comment describes it accurately
3. As a bonus you could also implement visualizations that an IDE would render like graphs or output values given various input sliders
There is doctest in Python for example that works in this way. The goal is to make sure that code examples embedded in docs always work.
Isn't that what Literate Programming is for?
I think for me, the biggest example of necessary code comments is the triple slash style comments that IDEs use. While I'm sure everyone would just say "Oh just look at the documentation, it's the same thing." In context, it's a lot nicer to look at the IDE description and format that you're used to, as well as see all the pieces of the code correctly syntax highlighted because of it. I also think that when working on smaller but semi-complex projects, having comments for others to help clean up your code or to return to your own code is great, and can make a good pair *with* good documentation. They should not be mutually exclusive in my opinion.
/// and /** */ are actually the same syntax that docygen uses. So you can easily write the ide description and then run doxygen to generate a nice(ish) html for your project that documents all the functions and variables
@@bspringer oh that's interesting, i will have to try that some time
Frankly, this really depends on the language. In some languages you can _encode_ basically everything. In others, it may be basically impossible in many cases.
The former ones are languages that include full proof checking systems, which (unfortunately) makes them pretty unwieldy in many cases.
Thankfully there are a lot of languages in-between. (Mostly these with expressive types.)
Totally agree, very well put. Manage to write code that tells WHAT is doing and not HOW is doing it, then comments disappears.
It’s a lot harder to express my rapidly dwindling sanity without comments though.