I added a comment here but then realized it wasn't necessary and removed it
@PureGlide
6 ай бұрын
My favourite comments to write: the link to the stack overflow article I stole it from
@ianbarton1990
6 ай бұрын
I believe you mean to say that you took "inspiration" from ;)
@trumpetpunk42
6 ай бұрын
I've definitely done this.
@etsequentia6765
6 ай бұрын
Agreed. (after I'm done rotflmfao)
@JorgetePanete
6 ай бұрын
Stack Overflow actually wants you to link back to the comment, as if code actually had owners or something 😂
@cpexplorer1701
6 ай бұрын
My mantra is “just because it’s called code doesn’t mean it has to be cryptic”.
@elephant_888
6 ай бұрын
That’s a good one!! 😂👍🏽
@Ariemeth
6 ай бұрын
I love this!
@ek3279
6 ай бұрын
I’ve heard this for 50 years. In my experience, comments should (1) identify dependencies that are not apparent, (2) describe reasoning for architectural choices, (3) significantly reduce surprise.
@7th_CAV_Trooper
6 ай бұрын
Maybe arc decisions belong in ADR docs instead of code?
@ek3279
6 ай бұрын
@@7th_CAV_Trooper That’s the point of ADR records - they go in the code where they can best alert implementers. Not everyone looking at code is writing the code - QC, security, and compliance folks benefit from them.
@lupita3689
6 ай бұрын
Also document/reference where certain parameters and information came, I suppose this fits in your #1; write down future optimization pathways (I almost never get all the time I need to perfect things on the first run), which expands your #2; and lastly, quick-start instructions if it’s a higher level construct (such as a class).
@Rick104547
6 ай бұрын
If relevant I would still put a comment in there pointing to that ADR record. Not everyone will look at ADR records so it might be easy to miss. But context really matters here. Ideally you want the code to speak for itself but in reality that's not always the case
@anakreonmh87
6 ай бұрын
Yep, nothing particularly new here. But I suppose it needs to be reiterated for the new generation...
@elephant_888
6 ай бұрын
The most beautiful code ever read a number of years ago had no comments either. It was a one page beautifully structured utility file, with fantastic naming and nicely sized composable methods. It wasn’t pretentious or trying hard to be “smart”. It was as if the developer had taken great care to speak through the code. I would argue that it crossed over into being a “work of art”. 🌟
@klausditrich7323
6 ай бұрын
Is there maybe a way to read it / git?
@elephant_888
6 ай бұрын
@@klausditrich7323 I got that code snippet from a friend in college over 25 years ago before GIT existed. 🤣🤦🏽♂️
@PeterHitchmanYT
6 ай бұрын
"This code was hard to write, it should be hard to understand.", always goes down a storm at code reviews.
@PaulSebastianM
6 ай бұрын
Most of my comments serve to warn against an urge someone might get to do X refactoring that seems natural, but that they wouldn't know in advance that it would break Y (performance) requirement, or in order to give more context to why something is done like it is, explaining a conscious decision that was taken in regards to a minor implementation detail. These cases are extremely rare, they don't fit into public interface documentation and are usually one liners.
@TonyWhitley
6 ай бұрын
There are many cases where some explanation of _why_ the code is written the way it is is needed. Here's just one example from some code I'm reading // NOTE: truncation code could be moved to DumpRawData method for reduced CPU use. // However, this causes memory pressure (~250Mb/minute with 22 vehicles), so probably better done here.
@7th_CAV_Trooper
6 ай бұрын
Agree. "monsters be here" messages are justified.
@trumpetpunk42
6 ай бұрын
@@7th_CAV_Trooper there's a pretty famous one of those in some major piece of software - I'm trying to remember what exactly it was
@alexaneals8194
6 ай бұрын
Comments should tell why a piece of code was written and not what a piece of code does. This function was written to prevent the company from being fined by breaking such and such regulation. For example at one company they had a function for calculating overtime pay in the US. For most states at the time more than 40 hours a week counted as overtime; however, for one particular state over 8 hours in a day counted as overtime regardless of the total number of hours worked for the week. Without a comment explaining this, someone could modify the function thinking that the > 8 hours was a bug and getting the company in trouble with the regulators.
@@richardneumann3335 Except the code was not written in C# or Java, it was written in SQL for SQL Server 2000. However, just the overtime_that_one_state does not explain why; it only explains what the code expects. Code can never explain why. When code doesn't contain comments as to why something was implemented and when those comments are not updated, it can lead to severe fines in regulated industries. Telling the government that the reason you underreported taxes was because you thought that the code contained a bug doesn't fly.
@boam2943
6 ай бұрын
@@richardneumann3335 That alone would not be sufficient since those two overtime definitions are for two different time scales. The first is for a single day and the second is for a week (between 2 and 7 days of work to go over 40h). You would need more code to validate that and fall again in the thing you seem to be trying to avoid (writing a function).
@alexaneals8194
6 ай бұрын
@luke5100 I think you miss a big point. Code can only tell you what it does. The example I gave above related to the state of Alaska where overtime could be total weekly hours > 40 or daily hours > 8. If there is no explanation as to why Alaska is different then one day someone is going to come in and look at the code and assume that it's a bug. They will fix the bug and a few days, weeks or even months later an issue will arise due to their "fix". A simple comment indicating that overtime for Alaska is a special case and that before you touch the code make sure that that special case does not still exist prevents those types of bugs. It doesn't matter how you name the function the variables if you don't comment the reason why then someone is going to assume that it is a bug.
@bernhardkrickl5197
6 ай бұрын
@@alexaneals8194 I'm with you in the general argument, but in your particular case I see different solutions. First, there should be a test ensuring that Alaska is treated differently. As soon as somebody fixes the "bug" the test should fail. Properly written and named, that test clearly shows the intention. Second, if there is a part of the code that says something like "if (state==Alaska) then calculateOvertimeForAlaska()" then this should be viewed as intentional by any reader and not changed without at least asking someone about it.
@bonquaviusdingle5720
6 ай бұрын
Comments remind me why/how I designed the code after I come back after a year. It saves me loads of time.
@mrmaxwell0701
6 ай бұрын
But what happens then when somebody updated your code and did not update your comments ?
@mrmaxwell0701
5 ай бұрын
@@SimonWoodburyForget When code is updated improperly if you're having good practices, a test fails. If not you may have the chance that the app breaks. At worst a bug will appear. Comments will not behave differently in these cases and they may be confusing when time arrives to debug. The responsibility of the developper updating commented code is to delete those comments and provide code readable like well writen prose.
@Zeero3846
6 ай бұрын
I write doc comments for the intellisense, but also to write specifications, because it's unruly to leave it only to unit tests. Visually, it's also helpful to see the big blobs of green on the code overview next to the scroll bar in editors like VSCode.
@tiberiusmaximilian5591
6 ай бұрын
The reason for docstrings is intellisense - working on a different part and getting a reminder what a function does when i am using a function in a totally different place. I am disappointed that Dave does not know that.
@hiftu
6 ай бұрын
There are 2 types of comments I usually write. #1, API doxygen style comments about the functionality of a function (sometimes add pre, post conditions if not clear) #2, Explaining decisions: WHY I choose that particular solution. Otherwise I try to name variables/functions accordingly.
@Immudzen
6 ай бұрын
The comments I like the most are ones that tell me why and where something comes from. So if you are implementing a scientific algorithm writing down what paper you are implementing is REALLY important. Another common one is if you had to do external calculations for something. For example if you have done optimization and profiling to come up with some settings for a solver then it is really useful to write down why those solver settings are used and where the testing was done.
@sarabwt
6 ай бұрын
I do agree, that having single line comments in the style 'a + b // sum a and b' is useless, but you can only preach expressiveness with code for so long. There might be complex functionality, a bug, quirky behavior that is easy to overlook or a business decision that is way easier to understand with one line comment than having to read the implementation or that you turn a double take into a single take. Even a '// yes, this could be probably simpler, but it is an implementation detail and idgaf' is ok in my book... If it's stupid and it works, it ain't stupid. For libraries/utilities it is incredibly useful to add doc comments that describe behavior and show how to use the function (even inside the dev team - people come and go, hell, even if you are the only person writing the code), saving you the time that you would have to read the implementation and also help you avoid potential foot guns. Having comments on function parameters about what they do and how they interact with each other is also super useful, saving you the time that you would have to google/read the docs/query an LLM/read the implementation. Documenting code is also a better experience in some languages take the documentation seriously, compiling and executing code snippets to verify that the code in them is correct, so you can have tests in your documentation. Elixir does this and Go does something similar with their exmaples.
@ComradeOgilvy1984
6 ай бұрын
Dave in the video mentions in passing the idea that a test is also documentation. When first learning a library, I am often scratching my head trying to figure out a few simple examples. Maybe there should be tests I should be looking at? I am just thinking out loud.
@sarabwt
6 ай бұрын
@@ComradeOgilvy1984Tests as documentation sound good in theory, but usually don't work, because you do and should optimize for ease of use for someone with knowledge about the codebase, and are thus not meant to be documentation. You might get a vague idea about the system, or what it should do, but the how and why is unlikely to be expressed with tests. On top of that, having to read all the tests just to potentially find out the answer feels wrong, as you are switching context constantly. Ideally you would want documentation to be documentation and code in documentation be compiled and tested that it does what it says it does. After that you could go looking for tests in the source, but it is rarely useful. For me it is usually more useful to just read the source and find out how things work, as I tend to find undocumented behaviors along the way that might make my life harder/easier or a way that I could hack the implementation to do what I want.
@jgharston
6 ай бұрын
Yes, that's the sort of thing where if you comment it you don't describe what the computer is doing, you describe the function that is performed. For instance it could be "add r2,r4 ; add the exponents". At that point you're reminding the reader that the two exponents you're manipulating are in those two registers, and this is the add-exponent part of the multiplication code. (Y'all remember how to do floating point multiplication, doncha? ;) )
@rightsdriven
6 ай бұрын
Mate, really wish you would drop the clickbait titles.
@trolltothebank
6 ай бұрын
I'm not a long time subscriber, but I know that some of this is just standard operating procedure on KZitem. I think a more appropriate title, that still retains clickbaity-ness, would have been something like "is commenting your code a waste of time", I dunno.
@justice7ca245
6 ай бұрын
his content is always on-topic and well thought out, the titles are a bit click-baity but if you know that it shouldn't be a bother?
@xboneyt485
6 ай бұрын
@@trolltothebank of course the person with "troll" in their name has the most level headed non reactionary comment 😅
@psychic8872
6 ай бұрын
He should add a comment in the title to explain that he is trying to make a more nuanced argument but the title oversimplifies that just to capture your attention and if you watch the video, you will have the chance to understand his argument
@nezbrun872
6 ай бұрын
I'm starting to wonder if he worked on the Post Office account at Fujitsu.
@lielfr
6 ай бұрын
100% agree. A particularly nice feature I like is "doc tests" in Rust, where each code snippet in doc-strings is ran as a test. I think it's really useful for documenting public APIs, as well as ensuring that the documentation examples are in sync with the actual code
@trumpetpunk42
6 ай бұрын
Thanks for mentioning rust doc tests. Today I learned...
@stevenleonmusic
6 ай бұрын
I don't write comments in production code 90% of the time because I rarely find a situation where they help describe the code better than the code itself. I write loads of comments for code I share with students because I'm deluded into thinking they'll somehow read them even though they can't be bothered to glance at a textbook or even pretend to be awake during my lectures.
@martinhsl68hw
6 ай бұрын
One of my criteria when marking my students' coding projects is 'how easy was it for me to get up to speed as a newbie dev on this project?'. Good comments can make a huge difference, not just for understanding the code, but for getting inside the mind of whoever was writing it.
@michaelrstover
6 ай бұрын
I am thankful the jdk includes quite detailed comments that explains what classes are and how they are used, and what the methods are for. Too many third-party libraries are full of just empty javadocs, and visiting their API documentation is frustratingly useless. Interfaces need comments that explain why they exist and how they're used. Probably most public classes and their public methods need the same (if they aren't a method from an interface - the comment belongs on the interface in that case).
@gammalgris2497
6 ай бұрын
Literacy has some prerequisites. I had coworkers that didnt understand recursion and more advanced programming patterns. So far readable code is subjective. If you modularize code then you have various code pieces with different abstraction levels. What also often is missing is value ranges/ allowed values and return values. Sometimes you want a custom type but some time you want a more generic type (i.e. lists, arrays, sets, maps, strings, numbers, etc). I'm aware that I will not get it right every time. If I revisit old code then I check it and update/ delete as required, comments too.
@tribble1
6 ай бұрын
Comments are code that doesn't compile, can't be tested so its literally always a maintenance nightmare.
@spectr__
6 ай бұрын
The same can be true for documentation.
@moestietabarnak
6 ай бұрын
issue when using abstraction and generic programming. sometimes comment can say what is NOT in the code and WHY. I've seen routine rewritten (in git history) 4 times to be eventually rolled back to the original with the comment like "this approach works, we tried using a common pattern 'x' but it doesn't work for these reason : xxxx
@sig7049
6 ай бұрын
I wholeheartedly agree with this video. In most cases, when I feel obliged to write a comment, I know it's because my design isn't ideal, but I can't think of anything better right now. So I consider the need for that comment a code smell. One thing I did recently though after writing a small DSL over a really ugly third party library, was to write a lengthy comment for my entry point. It gives a quick overview and examples to get started with my stuff. I consider that a useful comment (Ofc the reader might find and read my tests as well)
@MovOnVideo
6 ай бұрын
I reserve comments for when I have to make a hack to make something work or taken a shortcut that needs to be cleaned up later, as a hint to my future self or the next person to touch the code. The comment is there to explain why I made that "strange" choice and what the purpose is. In all other cases, in my opinion, the code should be "self documenting", it should be written with understandable names etc.
@spinnetti
6 ай бұрын
I code in assembler. I comment my complex bits of code so I remember what the heck I was doing when updating it months later. I don't do any fluff comments; usually inputs outputs and any tricky logic just after the function header. I also try to make the code by function and atomic to ease future maintenance or wholesale replacement.
@edgeeffect
6 ай бұрын
Another way to do this is to break the complex code down into well-named macros... the same way as people working with high level languages break complex functions down into smaller well named functions.
@cod3r1337
6 ай бұрын
So one of the valid reasons to write comments is when you hit the limits of what your language allows you to do to express yourself clearly in code. With Assembly, you are going to hit that limit a LOT faster than with, let's say, Python.
@mrmaxwell0701
6 ай бұрын
This reminds me a lot about Uncle Bob's Clean Code episode a while ago. Surprisingly these reminders are stil usefull.
@boam2943
6 ай бұрын
I normally only use comments to clarify what the code/function does (for complex templates, variadics or function overloading) or to provide examples of how it should be used (for complex functions that modify their behavior depending on how they are called). As an example, I once wrote a function that can be called either inside or outside a thread object and, depending on the method of calling, the code used to interact with it changes slightly. In all other cases I use automatic documentation generation. PS: @ContinuousDelivery Dave, you have a potential bug in your percentage calculation function. You are "/100" which is an integer division in most languages and you clearly want a double as stated in the return value. You should "/100.0"
@carpdog42
6 ай бұрын
Many times I have felt that I was bad at comments and tried to "be better", it never stuck. Prolific comments were seldom very useful, and I think I would agree that situations where one is writing libraries or APIs is the main place where prolific documentation comments are actually super useful. I have come to think of comments more as bread crumbs. I would even say there is an inverse relationship between the logic in my code and the comments. Logic heavy portions are short, well named, and limited in scope so as to not need comments. Logic light portions, where a function may simply be a sequence of calls, I am more likely to use comments as a sort of index as to identify portions that I might want to skip to. Often I find that rather than proactively adding comments, I add them after returning to the code and getting frustrated looking for something, so I mark it off for next time.
@BurninVinyl
6 ай бұрын
Where I can buy the t-shirt in video? it's literally me when I'm searching for something LOL
@Mercurio-Morat-Goes-Bughunting
6 ай бұрын
Same!
@noelpayongayong-dean5301
6 ай бұрын
Always plead guilty to this as it cannot be helped! I can make a decal on my own if he's wearing the last one, oh, dear me.
@tomcowell9653
6 ай бұрын
Absolutely. Docstrings should be used, but only to generate end-user documentation for a library/module. And this should coincide with writing the code, while it's fresh in the developer's mind. There are two cases for commenting changes: 1) if the project cannot be trusted to preserve the history 2) if the scope of changes is artificially constrained (fix this little bug, little man, without touching our perfect design)
@EschinTenebrous
6 ай бұрын
Enjoy blending 'both styles' into my writing. Clear code with good naming, and also prefacing each 'logic block' with a high level summary of what the following block or segment of code does. Such as,"Create if it doesn't exist;", then follow immediately with the code that checks and creates the folder if necessary.. More like a 'table of contents', so I can rapidly navigate lengthy scripts or libs. If both the comments and code are concise and clear, they act in a more 'symbiotic way'. I do draw a line though... I don't comment my import section, of course 😆 That's akin to 'teaching someone how to code'. Which isn't what comments are for... I've found I really appreciate this when I revisit code I wrote myself in the past. It always helps me dive back into code I haven't looked at in a long time, much faster.
@christopherguy1217
2 ай бұрын
All code should be commented. I've never worked on uncommented that was easy to understand or work on. Comments must answer 3 questions: 1) what are you doing? 2) How are you doing it? 3) Why are you doing it this way? Echo comments are never acceptable. I've never seen any code that is self explanatory. Everyone has a different view of what is clear and that clarity changes over time.
@chilversc
6 ай бұрын
I quite like the way go handles doc strings. They're more a human readable description and not just repeating the parameters. You're expected to infer how the parameters fit from their name and type. Part of the difference though is with public libraries the function cannot change what it does, only how it does it to avoid breaking changes. So library writers do not have to worry about the function changing with out updating the doc string. Instead they do have to worry about getting it correct first time as once published it cannot be changed.
@nickbarton3191
6 ай бұрын
I'd write a comment, but it seems self-defeating.
@Mercurio-Morat-Goes-Bughunting
6 ай бұрын
Starting out on an older Texas Instruments system (a programmable calculator running machine code) and a VIC20 with a Basic interpreter running on a gloriously expansive 3kb of RAM is where I learned to keep comments out of the code in confined to written notes. Coding in Visual Basic and HTML/CSS+SSI and XHTML/CSS+SSI with no environmental limitations is where I got spoiled and luxuriated by the opportunity to comment key lines of code. I still keep written notes. Some things just can't go in the code. So I knew from very early experience that there is a time and place to keep written notes and a time and place to to insert a comment or reference number/symbol in the code. Caution: This is a sole proprietor's approach to coding and may not work so well in a team where everyone "inherits" your work every day and no two people have the same internal dialogue language. And MAJOR props for the T-Shirt. That, by itself, would have been worth the👍 That T-Shirt made my whole day 😀
@YonoZekenZoid
6 ай бұрын
- do you right comments in your code? - nope! - why, what are they there for? - to annoy, confuse and become obsolete The best comment I ever saw was "WTF IS GOING ON HERE??? I DON'T EVEN", on a method that was 200 lines long. it was added after the fact. did anybody write a test? nooo! did anyone refactor? nooo! The comment is probably still in the codebase After watching the video, a comment I sometimes find useful, is when I'm copying and pasting code snippets off the internet in a hurry, I include the URL where the snippet came from. In an ideal world, I refactor the snippet(s) so they make sense immediately, but sometimes you can't do that... time constraints and whatnot... I feel it helps to have the guide handy when I finally get around to cleaning up the mess I made...
@Humakt83
5 ай бұрын
I somewhat recently left a TODO/FIX ME comment about removing a strange function after humanity kills the summer/wintertime conversion. Beyond that, I hardly ever comment code.
@dstrmberg
6 ай бұрын
You should not be concerned with the implementation details when using an API. Hence a short textual description of API usage makes it much, much, easier for the consumer of the API. If you write _deep_ functions and classes a short description makes sense. Comments also have their place in implementation code as well, when you are working with more complex algorithms that are deviating from standard design or implementation patterns (or for example to describe strange hardware interactions in low-level code). API documentation should never mention implementation details, since that is information leakage by definition.
@Pretagonist
6 ай бұрын
I write comments when I've selected a non standard solution due to external constraints. I also like to write headlines to make navigation easier when breaking code out into functions isn't optimal.
@junktrunk909
5 ай бұрын
There's a big difference between adding a comment for every obvious step in the code vs adding them sparingly to explain the intent of a complex piece of logic or as doc strings. The intellisense helper text alone is enough reason to always write doc strings for methods used outside of the current class. I fully subscribe to the idea that the function names and variable names should be chosen to be as obvious to their intent as possible, but it's silly to say "DON'T comment your code".
@christopherguy1217
2 ай бұрын
Writing comments that explain your code gives you the chance to catch and fix errors or poorly written or designed code. It's easier to fix a crock of s*** than it is to explain it away.
@npsit1
6 ай бұрын
I always comment so I don't have to try to remember why I did something 5 years ago. Or if someone else looks at it, they'll have an explanation where else a variable is use or why a calculation is performed. It saves a lot of work later. Put in the time to give yourself technical surplus instead of wasting time later trying to decode your code.
@daveblakeman6781
6 ай бұрын
Something I've looked for for years is a way of plugging diagrams into the code, viewable within an IDE - for certain problem domains at least. There are some algorithms where a single picture could literally save 1000 words. I've written a couple of plugins to do this, but it really needs doing at the IDE level to work well.
@vk3fbab
6 ай бұрын
The use of comments that annoys me is commenting out dead code. Sure if you're developing a major refactor do it, but don't check it in like that. Too many times I've seen developers reading this dead code and giving it too much consideration. We have version control to track old versions of the code. Use version control for storage of historical versions and comments for its communication purpose. Agree that code is the definitive documentation and that we should try to avoid comments by developing obvious software. One case I value comments is when there is a very specific set of config to make something work. We spent ages getting this config right for the database so please be careful changing this. There is a very specific bug this code solves. This code is in a very specific order and will break like this should you change it. Hopefully you don't get too many of these.
@josefsvitak4313
6 ай бұрын
//no comment
@vainoleppanen8971
6 ай бұрын
I am split. My mantra is: if you have nothing to say, say nothing. I.e. don't write docstrings that basically translate camelCase to "Camel case." Then again, I'd like to push the team to try to add helpful code comments and I I'd like to use linters. So I either write useless function and module docstrings or give up on clean linter reports; yes, I could also write "pylint:disable" comments. Just like compiler warnings, the only maintainable state is the clean state. So far I have opted to write the useless docstrings and push others to do so as well. Maybe one day I'll add missing-function-docstring and missing-module-docstring to the list of skipped Pylint checks.
@TheEvertw
6 ай бұрын
Personally, I use comments like section headings in a document. It helps readers get an overview of what is being done. Including me. I usually write these comments before I write the code. Very rarely, I use it when I have done something clever, though I try hard to avoid that. This means that comments are only needed when functions have several sections.
@astronemir
4 ай бұрын
I literally only write comments for the code review as we review each commit and it’s easier to annotate the code then to write up long commit messages that the reviewer will ignore anyway
@abbcc555
6 ай бұрын
You don't comment the what, you comment the WHY. pretty simple
@georgebeierberkeley
6 ай бұрын
If I went into non-commented code I’d be seriously annoyed.
@sylvainr0
6 ай бұрын
That's paintful to hear. So much young and not so young developers writing bad code AND not commenting it just because they listen to advices like this one. I agree that there should not be a lot of comments, but after decade of software maintainance, I can tell you that I'm very often staring at classes having no clue what they are used for. Since good and very good programers (those that do know that maintenance is much more expensive than development) are no so common. Therefore, we should encourage developers to comment. To comment wisely.
@matthiasoberleitner5942
6 ай бұрын
In sql more commenting makes sense. Imagine working in a language where you can only do anonymous functions and use constants... There you go that's sql development. Here comments make more sense in both explaining what you are doing and why you are doing it.
@mrmaxwell0701
6 ай бұрын
SQL is a query language, besides PL/SQL there are no such things as function signatures or variables to make the code readable. I don't think that SQL langage was the target of that video.
@Jakim_
6 ай бұрын
I write comments so that LLMs can learn what's going on ;).
@ErazerPT
6 ай бұрын
I try too keep my comments to "here be dragons" stuff, either because it's totally not obvious but must be done like that for {insert} reasons or because it might make no sense at all BUT has a damn good reason to be like that. The later is mostly related to "this external call says it does x but DOES NOT, thus we MUST do yz to do x".
@disgruntledtoons
6 ай бұрын
"This adds nothing to our understanding of the code." Sorry, but this is objectively wrong. Comments do greatly help a person unfamiliar with the code to understand it. They help us teach new developers how we go about things. They tell us what the code is *supposed* to be doing, which is information you won't get, even if you stare at the code for a thousand years. They well us where specific parts of the processing happen. They tell us about the overall organization of the code. They tell us the path of processing. They tell us what events trigger the code to be called. In my own 12 years of software development, I have lost far and away more productivity from needing a comment I don't see than from seeing a comment I don't need.
@philw3039
6 ай бұрын
Comments tell what the author intended the code to do at the time the comment was written, there's no guarantee that's what the code actually does because the comment is not involved in code execution in any way. I think for most coders the comments they encounter will be accurate enough to be helpful, but it's easy to take it for granted this will always be the case. Striving to create readable code is a more robust way of making the meaning of the code more transparent to other developers.
@bob_412
6 ай бұрын
I agree with everything stated in the video, but I want to add a little bit to the story. Working with closed libraries, legacy code and bad design software(Autodesk Maya) requires having workarounds and extra safeties that need to be implemented and there isn't really another way of doing it. Many times I would delete or redesign code that I've written months or years before, only to be hit with an error later, realizing why I've done the things I've done. Comments really help in that case to further explain things and prevent unnecessary work for a code that I alone use and maintain, and I imagine it would be essential for a group of people in that environment.
@philw3039
6 ай бұрын
Seems like automated tests would help in that situation. If you want to refactor/redesign code but find regression errors to be a barrier, then setting up tests to check key functionality could allow you to make changes with less risk. But if the software you maintain doesn't allow for that, then it sounds like you might have a technical debt problem, in which case comments are only really going to act as a band-aid.
@bob_412
6 ай бұрын
Yes I suppose some non-standard automatic tests could be implemented in my case, thanks for the suggestion!
@goosezen
6 ай бұрын
I've generally used comments to state my intent before writing the actual code. It helps me organize my thoughts while I'm doing it, and afterwards helps me understand what I was thinking when I was writing it. If there's a bug, isolating the part where the code doesn't do what the comment says it does can help hunt things down. Could this be achieved through better variable or method naming? Sometimes yes, sometimes no. Not saying don't make your code good and rely on the comments, but there's a difference between intent and implementation, and knowing where the intent differs from the actual results can be useful.
@mrmaxwell0701
6 ай бұрын
In my opinion that first part of your comment is what a test is meant to do.
@philw3039
6 ай бұрын
@@mrmaxwell0701 it sounds like pseudo-coding --- a popular technique to plan out a coding approach before writing actual code. But usually when people use comments to pseudo-code they delete them after they've written the actual code.
@mrmaxwell0701
6 ай бұрын
@@philw3039 The difference is that we keep tests because they prevent regression.
@user-de8bt9co8c
6 ай бұрын
Fully agree about the code being a human to human communication. IMO there’s two key points - the structure of the project should communicate what the project is about, functionally speaking - the code should communicate the algorithm/ the logic that is applied to respond to a given use case, as close possible as you could express it in plain english (the what) and express the how only in dedicated lower level methods . These lower level method could eventually worth a comment when the how is not obvious, like ie bitwise operations that are not immediately understandable. But as a general rule I tend to avoid comments, mainly because comments lies. Even if they are right at the beginning, that is absolutely not guaranteed, they will be quickly misaligned with the current implementation making everyone losing their time making assumptions based on wrong information. Actually, it’s like documentation. If it’s not at the center of the development process there’s chance never being relevant nor up to date . Side things never evolve synchronously, developers does’t have two phase commit actived . So the code can change but the side document not, nothing enforces it if not fully part of the development process.
@WyZtIx
6 ай бұрын
I think the issue is that people think docstring is used to explain what the method does. The docstring is the equivalent of your method contract. This allows a caller to know what potential values are allowed without looking at your code. For example, in the "display percentage", the docstring would state which values of "percentage" are out of bound (e.g. percentage value from 0 to 100) if there is any specific restriction. It's not intended for the user that looks at the code and try to understand it, but for someone using your method to understand what it allows. It is not that important for internal use, but as soon as you start developing a library, they are mandatory if you don't want to write 200 pages of documentation on how to use your library.
@tipeon
6 ай бұрын
Once, a client required that every single method was commented. We just ran a comment generator tool on the codebase and called it a day.
@YisraelDovL
6 ай бұрын
For weak typed languages (JS) , DockBlocks help the IDE catch type errors.
@edgeeffect
6 ай бұрын
Comments that explain WHY rather than WHAT or HOW are sometimes very helpful.... Oh... then you said that anyway. :)
@Yulrag
6 ай бұрын
I write comments to explain not obvious parts of the code or intentional empty if else branches (due to avoidance of using exclamation mark ! as negation in condition).
@caseyleedom6771
6 ай бұрын
I think that this video mostly falls under the category of "Click Bait" - an incendiary headline designed to pull outraged readers in. You actually had some vaguely useful comments but most of it was about examples of how bad most of the comments you see people putting in are useless. A much better video would have focused on constructive advice for how to comment code well in a manner which enhances its readability/maintainability/etc. ... perhaps with a headline more like "How to write the best code comments ..."
@NemanjaMaksimovic
6 ай бұрын
Write nice tests. They are executable docs/comments ;)
@balazssebestyen2341
6 ай бұрын
TLDR: Comment your code only when the code itself cannot be self-explanatory enough, e.g., when it would be ineffective to write a one-sentence function name. In some of those cases, commenting is crucial. So, let's make a video titled "Why You Should Comment Your Code," and then explain in a third video that "Well, It Depends."
@samuelaslund5873
6 ай бұрын
Trying to summarize the most important parts of good design in 15 minutes and mostly succeeding :-) I do not totally agree with the badness of function or class-comments tho. When trying to navigate a large legacy codebase I want to be able to glance att the context-popup from the IDE to get a little more info about a methodcall or parameter that is not obvious. In an unfamiliar codebase the abstractions selected is often not obvious and might change over time, thus a comment on why and what is often usefull. Also, in legacy code you can not expect that good design is kept all the time, thus again function and class comments become neccessary.
@amirnathoo4600
6 ай бұрын
Just because you as the developer carefully chose your objects and methods names doesn’t mean that others will automatically be understand what your code does. While I agree that paraphrasing the code in the comments is just silly. Documenting your function header should be required. The reason is that I don’t always have access to the code and having a reference that documents the APIs is extremely useful
@TomVahlman-bz9nj
Ай бұрын
JavaDocs are only needed in public (java) API:s. Comments are only used when devs are uncertain about the code they wrote is correct.
@phatster88
6 ай бұрын
Dave is destroying another fallacy, after saying no to pull request, e2e testing, agile..
@Emerald13
6 ай бұрын
I may have missed it, but I would mention the rise as well of tools like co-pilot which include code explainability features.
@danmabee
6 ай бұрын
There's a C# analysis rule, I forget which one, that encourages writing things like, "if ((a && b) || c)", the interesting bit here being the extra parens for "readability". It's essentially using language operators as comments, and is in my view equivalent to the assembly comments example you gave. It's only useful if you don't understand even the most basic order of operations of the language. I know coders who voluntarily write this way as well, but I don't see the point any more than writing something like "a = (b * c) + d". To me, it hurts readability because now I have to slow down and try to figure out what it is they're trying to override. Worse, in a complex expression the number of nested parens can get pretty hard to count.
@AlejandroMallea
6 ай бұрын
The idealistic view that code should be understood without comments only works in specific scenarios, including 1) all developers in the team are of high level, and 2) you don't share the code externally. There are many legitimate uses cases for comments that you're ignoring in your rush to rant against _bad_ comments. Library writers in particular need to document public functions and types with enough detail and corner cases to be useful for the consumers of the library without asking them to go and read the unit tests in the source code. Then you have comments that you write to explain architecural or design decision to your colleagues, knowing that if you don't, the question will come up in the code review anyway. Then you have similar situations but for code that might be too complex or abstract for junior developers in your team and you want to guide them appropriately. Also unintuitive exceptions that need to remain there because of some business case exception, as others have mentioned.
@PatrickMetzdorf
6 ай бұрын
Nowadays there is a new type of audience that benefits from comments, which is AI tools. Yes they do also benefit greatly from code being clearer and well-named etc. But comments that add important reasoning and context surely makes AI-analysis more effective, as well. That said, what format or what type of information makes the most impact in aiding an AI to understand the code, is probably worth a study.
@jjmalm
6 ай бұрын
Writing code without comments is like saying I can write an article without footnotes, endnotes, abstract, and references because the reader should be smart enough to understand the text and context. I agree attempting redrafts to reduce comments, but at some point you have to move on
@BurninVinyl
6 ай бұрын
/* Don't trust the comments in the code also don't believe in everything on internet - Benjamin Franklin */
@TheJimNicholson
6 ай бұрын
Comments are often a proxy for comprehension. Developers who insist that other developers write comments typically aren't willing to spend the time actually reading and understanding the code as written.
@bobchannell3553
6 ай бұрын
I love the click bait title "DON'T Comment Your Code". Just wanted to hear what he has to say. I listened to the first few minutes of it, and that's all I have time for.
@runonce
6 ай бұрын
Loved the tshirt.
@larsmielke9400
6 ай бұрын
Not writing comments might be possible in a world with highly specialized programers. In today's world, that is just unrealistic. For example, if I write a C extension for a Python program , I cannot spend 2 years to learn all the nifty little detailed nuances to make my code correct, fast, short, concise and intuitively readable all at the same time. I want the code to solve my problem! So as a common courtesy to the poor ba*rt who inherits my work, I add a comment. Even in languages like Python, comments are often needed. Performance optimized numpy for example is unreadable by definition.
@nihorothereal
5 ай бұрын
Nice! How about documentation? Good old drilled and drilled documentation. How much should one write? I come from operations, where we only had discovery at our disposal, no documentation, we created it as we go. But how much of the documentation should a developer create? This works like that, A connects to B through gAmma in a way of theTA. At what level of abstraction, explanation detail, standard, templates (we had some just loving the word template, but it never worked)?
@therealcaldini
6 ай бұрын
My comments are for my Swiss-cheese brain.
@jornejongsma
6 ай бұрын
Everyone should view that talk about Clean Code by Uncle Bob. It's a long but quite fun talk to watch. (not) Commenting is one of the important subjects.
@leerothman2715
6 ай бұрын
I do like his quote ‘comments are a failure in expressing your intent with code’.
@Zeero3846
6 ай бұрын
!!COMMENTS ARE NOT VERSION CONTROL!! If you need to keep code around, control it with a flag. You have never needed to uncomment any code you previously committed as a comment. Even if you did, you probably broke production for longer than it needed to be because you had to recompile as opposed to flipping a flag that reverted to old behavior.
@iaina3251
6 ай бұрын
They're not but they can be very useful for your support teams when something breaks. Being able to open up a file in production and instantly see when it was last modified and by who can be a massive time saver for them.
@TonyHoyle
6 ай бұрын
@@iaina3251That's called 'git blame'. It's just not necessary to pollute the codebase with old code.
@mysund
6 ай бұрын
99% of all backups taken are also a useless waste of time.
@PhilipJReed-db3zc
6 ай бұрын
I agree docstrings are overdone--most useful for an external API when a self explanatory name isn't feasible. My team likes to see them in PR reviews though (yes, i know...) and this isn't a battle that makes much sense to press for now. Give a little, get buyin for more important process advocacy issues. 3:35
@75yado
6 ай бұрын
Well my approach is when my code still contains comments, it's not finished yet. My last step before commit is removing comments
@pierrelautrou1210
6 ай бұрын
The worst comment I came across was along the lines of "Comment to please Sonar" ...
@jaredkey542
6 ай бұрын
"Comments are for people who don't understand the code/syntax, so I don't see who the audience is." ... it really doesn't matter how clear you think your code is or how obvious something appears to be, other people can always get confused along the way. If you feel like your comments are useless, maybe it's that you are just repeating your code in your comments instead of providing more/better context. I found the assembly comments you showed very helpful, because I don't read assembly every day, and it was good to have a plain explanation for what was going on.
@Hofer2304
6 ай бұрын
These comments were a disaster. They may be okay in the first hour of a tutorial, but later I want to know why are these values stored in these registers? Please don't write the obvious in the comments, because you tell the programmer "Don't read the comments!"
@the-niker
6 ай бұрын
In complex cases I only write comments and end the function with NotImplementedException. Then I slowly turn every coment line into a function call and remove each comment when I'm done. Then I forget the exception in there and get roasted by the runtime.
@edwinschaap5532
6 ай бұрын
I support these comments.
@bobthemagicmoose
6 ай бұрын
The core principle I agree with but, after dealing with tons of nonsense code that has no comments… it’s far easier to add some explanatory comments than to create a perfect level of functional abstraction that is more understandable on a granular level and an overview level. Adding a single comment usually beats extracting the code to be its own function. It’s a balance to be sure…
@DudeWatIsThis
6 ай бұрын
Some virgin with freckles and buck teeth: *int _user; // This is the id for a user that hasn't been created yet, but will be created in the future* Maximum chad with a mighty square jaw: *int _userIdForAUserThatHasNotBeenCreatedYetButWillBeCreatedInTheFuture;*
@TonyWhitley
6 ай бұрын
It would be a _delight_ reading your code if _userIdForAUserThatHasNotBeenCreatedYetButWillBeCreatedInTheFuture is used 20 times in a function, a signal to noise ratio close to zero.
@DudeWatIsThis
6 ай бұрын
@@TonyWhitleyHow would you use _userIdForAUserThatHasNotBeenCreatedYetButWillBeCreatedInTheFuture 20 times in a function? The user has not been created yet. Once it's created, there's probably an instance of said user that we'll pass around instead of using this variable. Wow! You can infer so much behaviour from a single line! Now THAT's what I call Clean Code!
@TonyWhitley
6 ай бұрын
Substitute _someOtherRidiculouslyLongVariableNameJustToUseAsAloopIndexOrSomething Whatever it is it will result in horribly verbose code with any meaning lost in a forest of camel case.
@DebSchwartz-yn2on
6 ай бұрын
What does the person's sexual experience and physical appearance have to do with their code? (Nothing at all)
@weaksauce9999
6 ай бұрын
or design the code such that a variable doesn't need to be defined for a user that doesn't exist yet
@cetin9361
6 ай бұрын
Actually, unless they make the code easier to understand, *at best* they are useless, at worst they are much harmful noise in the code and sometimes actually make the code much harder to understand in the case that they were not properly updated with the surrounding code.
@TonyWhitley
6 ай бұрын
"unless they make the code easier to understand" You've destroyed your own argument, that's exactly the point of comments, to be able to understand what a bit of code is doing without having to read every last nitty-gritty detail of how it _implements_ it.
@cetin9361
6 ай бұрын
@@TonyWhitley I'm not sure I understand your point. My main argument was simply that when comments are not useful, they are often not _merely useless_ but the existence of useless comments can also easily become _actively harmful_. Also, I believe that the main purpose of code comments are not describing what the code does. That goal actually should be fulfilled by the structure of and the abstractions in the code. I think comments should mainly note the intent of the developer if it is not abundantly clear from what the code does, i.e. not the _what_, but the _why_.
@christopherpetersen342
6 ай бұрын
some good ideas but many assumptions about coding environments, tools, and the people (or AI tools) reading our code later on. anything that's not in the file with the code can be easily lost when changing tools or grafting tools into pipelines...
@Fanmade1b
6 ай бұрын
I really don't like the clickbait title of this video. My approach is also to always ask "why?". Of course, writing a comment "returns the id" on a "getId" function is redundant and useless. But in my last project alone, I've had multiple instances where we lost work days because existing code wasn't properly understood. It was already over-engineered significantly so that you could write a tool to completely auto-generate it, and the names were all perfectly structured. But there were many business requirements that you just can't know beforehand without having read very specific documentation or talked with certain people about very specific use cases. These included different processes depending on particular parameter values or architectural decisions based on the behavior of external APIs. If you have self-evident processes and functionalities that can be explained in a short sentence, you can and should try to name the functions accordingly. But even if you cut your functionality into tiny pieces, there is often a place in the code where all those tiny pieces are executed. Then you have to check that particular place and read through all the functions, sometimes going through them and all their abstractions to get a picture of what's happening there. If you have to do this, adding a comment to that place is usually beneficial. Because this code is maybe only written once, but it is usually read a lot more times than that. So, in my opinion, comments usually help when they either explain any non-obvious (business) use cases leading to the following code or reduce the effort required to understand the following code. Even if you try to avoid it as much as possible, you often have to have some places where something complicated happens in the code. So even if any developer can understand it by studying it for several minutes, you add a lot of value by adding one or two sentences of explanation. This should take less than a minute, but I guarantee that anyone reading this comment in the upcoming years, including yourself, will appreciate it. A caveat is, of course, keeping these comments up to date. But even though I often hear this argument from other devs who don't like writing comments, I can't think of more than half a dozen cases over the last 15 years where I saw a code comment that was really out of date in a wrong way. So, this is negligible. And one more thing: You mentioned that it is not your job to explain the language to the person reading the code, and I agree. Even though my career actually started off way better than it could have because, apparently, someone thought differently. When I started my first software development job, I was put as a single person into a large project where I didn't even know the programming language yet. So I was very unsure about it, which I made clear to my boss, but we both agreed on a two-month trial phase during which I would just try it. Looking back, the code was far from perfect, but it was exceptionally well documented with comments. The person who wrote it explained every line to a person they were teaching how they approached and solved the individual problems. It was so extremely helpful and improved my understanding of the existing code and my productivity when working with it that, after less than a month, my boss approached me and asked me to stop the trial phase and become a proper full-time employee instead, which I agreed upon. You never know who will read your code and why they will do it. Especially later in your career, when you gain much knowledge, you will often change how you think without realizing it. So, if you're approached by someone with less experience, this gap in knowledge and experience can quickly lead to misunderstandings. When I write code nowadays, I often think back to the earlier years of my career, when my thinking was quite different. I even argued with more experienced developers because I couldn't understand what they were doing, and they could not properly communicate this. So, when writing my comments, I explain them in a way my past self would hopefully understand. So, if anyone with less experience
@jonathanhirschbaum6754
6 ай бұрын
Comment WHY you do, not WHAT you.
@leerothman2715
6 ай бұрын
Totally agree. I can probably use the fingers on one hand to count the amount of times I’ve used a comment in the last 10 years or so. Funnily enough that’s about the same I’ve been practicing clean code & TDD.
@e-frame5344
6 ай бұрын
I comment bcs i am a junior in programming and sometimes have a hard time remembering WHY i did something :)
@PavelHenkin
6 ай бұрын
Nah man, I'm a 'senior' - and it never changes. Keep commenting, it help future devs including you.
@TonyHoyle
6 ай бұрын
It doesn't get better. You'll be cursing the idiot that wrote a routine before realizing it was yourself. I do it regularly. My main rule is keep it simple.. avoid 'clever' solutions when a simple and obvious one will work, even if it's a little slower (unless you're optimising a critical path that time won't be noticed). Your future self will thank you.
@kevinmcnamee6006
6 ай бұрын
At about 12:00 into the video Dave says that software languages are for human to human communication. I totally disagree. Software languages have been designed to enable humans to tell computers what to do. Adding comment to source code can help people understand what the code is supposed to do. Comments should at least describe what a routine expects as input, what it does, and what it generates as output. Explaining any tricky aspects of the algorithm also helps, as do links to any external documentation.
@ContinuousDelivery
6 ай бұрын
Sorry but I think that you are wrong, a stream of bits is THE ONLY THINGS A COMPUTER REALLY UNDERSTANDS the reason that we encode streams of bits as programming language statements along with all of the translation and checking involved is because we are terrible at understanding a stream of bits. So ALL programming languages, from assembler up, are designed to make that stream of bits more understandable for us. The earliest computers were programmed, literally, by flipping switches on their front panels.
@kevinmcnamee6006
6 ай бұрын
Yes I agree that programming languages are designed to make programming easy and understandable for humans, but they are certainly not for "human to human" communications. I'll stick to Python for the computer and English for the humans.
@BangsarRia
6 ай бұрын
You have a sophisticated audience that values your insights into CI/CD and Engineering Room interviews. Comments in code is better covered by other channels in a series on Clean Code for relative beginners. I work very hard to eliminate comments from my code, but I don't take any coding advice from you. As you British say, "Don't try to teach your grandmother to suck eggs".
6 ай бұрын
I've forgotten the meaning of Clean Code... That's code without comments, right?
Пікірлер: 243