@@ThePrimeTimeagen He was a visionary. A world where you don't need comments to navigate code. He invented JDSL to accomplish this goal, a true Genius.
I agree that senior developers definitely should have made him aware of such a huge vulnerability. I also wonder how something like this was pushed to production. I thought the json metadata was calling for specific revisions of these methods, so you can always maintain backwards compatible dependencies; his changes shouldn't have effected production unless he updated all the metadata to point to his new revisions as well. If he changed so much stuff, why wasn't any of it reviewed? Seems like this company had really bad organizational issues, which allowed for a junior developer to make sweeping changes without oversight.
He didn't have to implement them, it's a first class feature in the format he selected. Because he's a genius. { "comment": "this is a JSON comment ~Genius Scott" } The noob that didn't understand JDSL put the comments in the javascript.
The best comment I have ever seen in a code were: ! fiddle with variables and print stuff It was in a very old Fortran code for doing configuration interaction calculations for atomic nuclei.
I once came across "a squid eating dough in a polyethelene bag is fast and bulbous" in a source-provided library. I suspect I was one of the few dev's reading that code who got the reference.
With the qualifier "most of the time", I absolutely agree. Just yesterday I was cursing my heart out, because code was changed to do the complete opposite of what the comments said. Nobody maintains them, half the time people don't even read them and it takes on average 2 weeks before "redundantly repeating what the code is telling me already" turns into "blatantly lying to my face".
Why don't code reviews catch that? Odd. "Your comment here is useless. Report to the flogging station immediately." "This comment has nothing to do with this code. Flogging station." People would catch on eventually.
@@herrpez I wonder if some of those useless comments can be blamed on certain teachers. I remember at university they told us "for each line of code, there should be one line of comment". You can guess what the result of that was...
This problem arises when people write in comments what the code does instead of what it should do. "Setting timeout to 5" is useless and potentially misleading "waiting till work process completes first cycle" is usefull - even if you change timeout to 15 or replace it with conditinal wait. Or even if someone "corrects" the code to oblivion - feature maintainer will know what you WANTED to achieve here. And personally - I just like to mark "difficult" parts of code with prayers to Omnissiah or Cthulhu :)
@@herrpezI guess because people don't look at lines that weren't changed, and if comments stay the same, that means there's nothing to look at At least that's how my brain works
Linus torvalds said it well: Dont describe your code, describe why you are doing something (if it's not obvious). It's because otherwise the comment does the same thing as the code, so your code should be readable so you dont need comments. But sometimes you need to write code in a specific way for uncontrollable reasons (external issues such as driver issues, some external service behaving in a weird way, some library requiring something that is not obvious, etc).
@@doughxDude87 No. Even if you're doing the most complex computations imaginable, you can explain WHAT the code is doing 2000x better with the actual code itself, rather than some comment saying it in English (just like everything said in the video). Everything said in the video applies to any level of complexity.
@@nerdycatgamer sure there probably is a way to structure the solution to be better. But is it really the worth the time investment to refactor something that can be easily explained with a comment? All depends on the problem and time resources
If you can make your code readable enough and good enough, don't write comments. If you can't, Id rather have a commented steaming pile of garbage than a steaming pile of garbage with no comments at all.
Late reply, I know, but what makes you think that someone who can't properly convey their ideas through code would be able to convey said ideas through words?
@@longlostwraith5106sometimes it is that way because you have to work with legacy code and structures. You cant reasonably alter everything so its readable by code only. You dont have enough time and resources to be able to do that a lot ofnthe time.
@@longlostwraith5106 I've seen this and was able to understand what was supposed to happen, delete their code, and fix it. Talking to people and to computers are two different things.
I honestly don't care that comments can lie I'll take 75% accurate with some context over no comments any day The real issue is that comments need to be reviewed with the same scrutiny as the code they're describing
I think that comments should be written to summarize rather than to explain. The "write readable code" argument doesn't really work when you still have to read the entire codebase to see what's going on. And it's usually easier to summarize in a few sentences than aLongAndVagueFunctionNameThatsHardToRead.
Yes! I am admittedly very bad at updating comments. But at my last job, part of the review process was making sure your comments are updated. I would pretty consistently be told to update my comments, but the code looked good. Comments, to me, are incredibly useful, even if they're just directed at yourself. The problem with comments, just like code, is maintaining them, and making sure they stay relavent, just like code! The problem is not comments. The problem is a review process that does not see comments as useful to review. People just kind of glaze over comments. They should be reviewed just like code.
But how do you test comments? Nothing comes to mind as far as having some automated system judge comments. Unless we start using some framework that now reads all comments? If I can't test it, I'm way less likely to use it in my code. Comments fall under this as well. I hardly use them, save for a very reluctant to-do (don't-do) that I try to immediately get rid of ASAP. I'll read them, but at some point, I can get away with re-factoring large functions without needing to know precisely what they do.
Real talk: I usually only put comments in code (be it JS, R, Python or SQL) when i am referencing a business rule that needs to be understood. Preferably simply listing the business document link so if code needs to be updated they can go in-depth as to 'why' something is the way it is. I've found this is a big help in research settings where government & sponsor rules and regulations shift ever so slightly quite often.
@@mattmurphy7030 Another extension: Linking to Github Issues when you need a workaround for something that's currently not up to the documentation spec.
Rust is the first language where I felt like comments were right. The language is descriptive enough that I dont often need to write comments explaining what's happening. The built in testing system means I don't need to write comments explaining edge cases or intended use. Docstrings with tested examples are probably the best documentation I've ever seen in normal library code. Obviously other languages can avoid comments too, but in the looser or harder langauges I need comments more.
@@KManAbout Doctests will execute the tests in your doc strings. Tests can be nice as you can get chatGPT to implement your function for you from the tests, you could program your IDE to show you values flowing through your program from the tests, you can convert tests into types. However, make sure you are testing the properties of your function as they pertain to your business needs not the implementation details.
I need comments in any environment where i might be 'in the process' of developing a solution to a problem, rather having already solved the whole thing in my head, and I am now just fleshing it out with the obvious and perfectly well behaved and well formed code structure that I have somehow worked out. Or in other words; code is a process. Bad code and bad non-code descriptions need to be possible to represent while you don't have perfect alternatives at hand. If I didn't have comments, I'd just have documents in my source tree referring to specific spans of coude in the source files that the document is talking about. Essentially, comments with a bunch of stupid extra steps. I do get the motivation behind this conclusion; you don't want your codebase to be littered with crippled code that needs comment crutches to make any sense. But at some point in the development process, you need to set this aside and write bad code. So you can get around to writing bettter code later.
That only applies to those who are just calling APIs and barely have any advanced logic in their code. When you have advanced mathematics and complex algorithms and equations that are based on geometry, you'll need to explain what are you doing and why and why didn't you go for the other obvious more intuitive way. That's what comments are for. It's not to explain what's happening, it's to tell you why it's happening and what was the developer thinking.
He states it himself he's not into math. But math is important for a lot of advanced uses. Scalars, vectors and matrices for example are prominent in a lot of areas where transformations are used. never hurts for a programmer to know how to use advanced algorithms. Who knows, he may realize he can heavily optimize something with it instead of just looping through arrays like a novice. That's fine at the small level, but with large stores of data the processing goes through the roof.
I mostly explain the algorithm in a paragraph inside the function but at the very top of the block. Most of the comments inside the algorithm are just saying what if conditionals mean where it isn’t obvious. The most common example being at the top of an “else”. Like if I have an if block “ if ( size < max ){…” I put “max
As an embedded engineer, even if your comment is "this code is f'd-up" and at that point, even if it's a lie --- it's still a warning that it is not going to work like what you will work like what is epxected. That's huge. That's helpful. I worked with this stuff that was only very loosely embedded-to-JS, and copying it immediately via clone seemed silly --- but the comment saying, "this is f'd-up, I get it"... GOOD STUFF.
I'm a beginner, this kind of videos frustrated me a lot because of the titles "don't write comments", "don't do this", "dont do that"... And, a beginner life is like: -> Starts to learn about comments -> Start learning how to comment well -> Start commenting well =-=-= 1 Week Later =-=-= *RUclips video telling you to not write comments* Beginner Conclusion: All you've learned is wrong. =-=-= Sometime Later =-=-= -> Starts to learn about OOP -> Got used to OOP -> Start writing good OOP code =-=-= 1 Week Later =-=-= *RUclips video: "OOP IS WRONG", "OOP IS THE ROOT OF ALL EVIL"* Beginner Conclusion: All you've learned is wrong. And this applies for all of the things I've done. ALWAYS, sometime later, a video will show trying to discourage me or prove that what I'm learning is wrong and it shoudn't exist. I bet if I start learning Rust, 1 week later, a video will show to me telling that Rust is "bad". But I don't fall for this anymore. I learn by myself now.
Yeah, that’s because nothing is 100% the absolutely correct thing to do. There are debates and tradeoffs to most things. Writing good comments is good, writing bad comments is bad. Using OO can be good for modeling, using OO can have bad results for program structure and performance. Just accept that nothing you’re learning is the absolute end-all-be-all and understand you will eventually learn a flip side to what you’re doing. Eventually you’ll know enough that you’ll have your own opinions and you won’t worry too much about what some guy on RUclips says. Like this video, you’ll hear the useful parts and shake your head at the dumb parts. You’re ahead of the curve realizing that anyone claiming to have THE answer is going to be contradicted later. Every new framework and paradigm that gets introduced as god’s own work is eventually replaced. The problem solving and learning skills you build are what matters. The tools always change.
While I'm not a beginner, I recently started getting back into coding after several years away and I feel this from videos I've seen. My method has just been, 'appreciate what's being discussed, and then continue doing what you're doing, perhaps applying this new information to it'. In my current code for example, I'm commenting _every_ function, specifically so that I have reminders as I warm back up to coding. Once I'm more on a role, I'll feel more confident removing comments or narrowing them down to just pointing out why sections appear weird.
Good man, the takeaway lesson is to take onboard someone’s claim or opinion, but don’t believe anything until you’ve tested and confirmed for yourself. It can take a long time to do this so don’t try and pick a side until you’re satisfied with your understanding. Someone says comment intent, someone says don’t and make code clear to understand, maybe a one-size-fits-all is actually never the answer and the fact is it will always depend on situation and circumstances, keep doing more of what works best for you and do less of what doesn’t. It’s like mastering any skill, masters never stop honing their craft, don’t look for a finish line, rather enjoy the journey and recognise that when you hear opinions or blanket statements like this that one day you will have found your own foundations from experience that will no longer be shaken by others. Your journey will be yours and nobody else can tell you the right way to go, because nobody else can take your path except you. ☮️ ✌️ 💻 ❤
Sometimes you have to use libraries that have such convoluted interfaces and unintuitive names your code will become unreadable just due to that. In some languages that includes the standard library..
50 year veteran here. If you have ever come across code you wrote 30 years before and thought "WTF was I doing this for?" because you know you had a really good reason but you can't remember what it was, then you know why comments are crucial. As a team lead I would refuse to OK code that doesn't tell me what a piece of code is supposed to do without having to read the code. It should also tell me the reasoning if anything is "non obvious".
Lets say, hypothetically, if there was a way to somehow let people know how the piece of code works without writing comments. I mean, what if there was a document, somewhere in confluence, that told specifically how the code works, which type of response to wait for. I can't think of something like that existing.
I think using comments as headers to segment areas of a large code blocks, is something useful. It allows quickly skimming through code, without having to read the whole thing.
@@ScibbieGames if you have such a big thing that you need to write segment comments, usually you could instead use the time to comment it to just split it into different files/classes in the first place and then wouldnt need the comment any more.
This guy’s voice is awesome. Like, I never thought I’d be able to tolerate a voice like this but he’s even more hilarious because of it. I can’t get enough of his videos.
Here to the clean code camp who say the code should document itself: This is what your function names end up look like: - setupPageSizeA - navigateToSectionFourteenParagraphThirtyTo - handleTopLeftCornerButtonClickWhenUserIsUpsetAndFrustrated ... The names are so meaningful that you don't need to write comment at all. And Shakespeare shall be proud of ya.
Lmao you're retarded, in reality what you wrote looks like this: setup_page(page_size::A4) navigate_to(section(14), paragraph(32)) on_feedback_form_button(callback parameters...) And yes it's perfectly readable and you're a braindead moron, your forced use of camelCase is proof enough but your attempt at naming is just as bad.
this is hyperbole. You can easily create concise names that clue in to what the code is doing. you just sound like youre bad at naming. Names should be clear and concise to function. Comments should be added when that isn't sufficient. It's not hard.
Comment now perfect later. Comments are context. Beginners need context and have to learn to communicate it. Technical writers need context to document. Senior devs create context and have to clarify it. Managers and stakeholders need explanations from everyone else depending on that context. The idea of not commenting is arguing for a perfect ideal code that will never exists. Just comment.
You know there were these kinds of exceptions listed in the video, right? You actually watched it, and didn't just comment after reading only the title, right?
the comments should be about the design rational, the trade offs, business requirements and context. If you're writing a library that calls some other service, the comments should be about the quirks of the service and any odd stuff that you found. The comment should be about "how do I help someone maintain the code."
Me writing comments for my future self has saved me, sometimes just the why, sometimes some what's to make a piece less dense (sometimes I write dense code when I'm in a flow, but I won't be in that same mindset a year later). The best thing to do is to write comments to someone out of the loop just to bring them to speed. Put it where it matters, so if that specific thing changes, so does the adjacent note/comment. Those that don't give themselves/others future notes have not ran into that issue. After they have the experience of going into different projects and having to revisit the past and realize they can't put together what they thought was obvious, they have to read a bunch of code to catch up to that mindset for that moment, then they'll have wised up to what to put, where to put it, and smart enough to keep those important bits up to date.
At my job we often end up going over the code in a pair of reviewer and author. If at any point we need to stop at a piece of code to explain why it's the way it is or we stop because even the author needs to think about it it's always a three step process 1) what does the code do exactly? 2) Can it be simplified or cleaned up? 3) If no, put a commend explaining why the code is the way it is It's a rare occourence, oftentimes to adapt some weirdness from a third party library or incomming data. But when it happens the comments do actually help. Basically: If you read a line of code and your first thought is "WTF is this?". It's probably time for a comment
I am a fan of triple-slash comments in C#, my thought is that if you need a comment inline, it probably should be it’s own function and then inside the triple-slash I can detail what is being done, what are the concerns for the comments, and why did I decide to do this. It also allows me to explain concepts. It also can be used by auto-documentation tools to make documentation. And then there is a team effort to update and scrutinize the comments when we change things up such that people can better understand. Self-commenting code has been a nightmare to work with in the past, because evaluating decisions for refactors suck.
++ comments for methods are truly helping, and every library should use it. If a method doesnt have this intellisense comment, i always get a little angry.
These are called "doc comments", and I think that they originated in Java, which is a language that, like C#, I don't want to use for anything if I can help it, but the doc comments are a good idea, which is why Rust has them as well.
3:04 Human hability of choosing some two random values: 77 and 69. 7:01 C++11 optionals comes from boost::optional (introduced in boost in 2004). If you mean the origin of optional has a "programming idea", not sure, but it's an idea that comes very naturally. It's very likely that a lot of companies and even personal projects have introduced some kind of "optional" type from themselves years before boost.
Software Engineer speaking: I will ensure anyone who doesn't use/maintain clear and concise code comments will be assigned as far away from a keyboard as possible.
@@shinobuoshino5066 Yeah no, I've seen enough piss poor code written by EE's moonlighting as proper Software Engineers where I am tired of wasting time and effort trying to decipher what the hell you were attempting to accomplish. If you can't clearly document your code, I will ensure you never touch a keyboard again.
My first computer science teacher made us write out what our functions were going to do before we could code. We also had to put in the comments which function was calling which. It is actually easier to run my code through an anti comment program (just deletes any thing in a ‘’’ or after #) than to break this habit unfortunately.
@@shinobuoshino5066 I know this might seem stupid. But they wouldn't even let us use IDE's. The teacher was from a country where they were programming using Notepad++ as the IDE. Imagine all of this and then on top of it, they exclusively taught OOP in Java at the time, too. Safe to say, a lot of ppl were scared away from CS by this entire experience.
10:40 - Not all HTML tags require closing tags, and I'm not referring to self closing tags like . It goes back to the early days of the web, when you wanted to send as few bytes as possible over the wire. The HTML spec allows you to omit closing tags in some cases as the other rules in the spec prevent ambiguity. If you don't follow the spec of course, all bets are off. I saw some of your chat saying it's a new thing, this is false. It's always been the case.
Maybe it’s just because I mainly do embedded programming, microcontrollers, FPGAs and similar, but comments are very useful sometimes and I would rather commented code than non commented code, if the comments don’t make sense you can always fall back to just reading the code.
I had a number of issues with the original video when I first saw it. It's basically "bad comments are bad" behind a misleading title. The example at 7:48 just deepens that tautology. Yes, absolutely 100% construct your code to do everything you can to not need comments. But yeah, absolutely write a comment if you're doing something weird or if some context will help someone else out or speed things up. Basically, just try to put yourself in someone else's shoes and ask, "Would someone else immediately know what the hell I'm trying to do with this or would this seem pretty cryptic?" The thing may be obvious to you after 3 months mucking around in the codebase but is a newly onboarded junior engineer going to be baffled? At worst, a stupid comment like the one at 7:48 is going to be disregarded when it's recognized as out-of-date. "Don't throw the baby out with the bathwater" blah, blah blah.
I find comments that explain the code useful in two circumstances: 1. As a block comment at the top of a file, summarizing what the file does 2. Comments breaking up sections of a large procedural function that does several complicated steps. Many people will say "if you have several complicated steps, you should just split them into multiple named functions". But I disagree with this. When you split them into functions, you're implicitly saying "these functions can be called Independently, and perhaps in any order". But in the case of the large procedural function, each step must happen in a very specific order, and the steps shouldn't be invoked in isolation. Having them in order within a single encapsulated function is much better for expressing how it should be actually used, and comments can just help summarize what each complicated step is doing, and provides a little break between reading each section.
Wait... even if you're using C, you can still introduce a block. Declare variables that later portions need before the block, then have a block of statements that do some related work and initialize your variables, and boom: a section without comments. Repeat until your big function has enough sections to be comprehensible. Maybe the variables from each block will say why the block exists... or else you add a "why" comment, so #2 is just a special case of #1.
@@okuno54 yeah, sometimes you don't need comments in each section. Sometimes you do, because the variables don't explain it well enough. I use blocks in C all the time
I've been struggling with a relatively short function as of late regarding datetime conversion and various adjustments with a dynamic axis. The code is commented a lot and it has taken me over a week to understand it. Functions and classes are intertwined, most variables are kept short for whatever reason, lists and dicts are unpacked into objects, functions are passed in init, of course no type hints (yes, it's python). A simple thing like using longer, easier to follow variable names would solve so much and dynamic typing is the absolute worst thing about python.
@@ThePrimeTimeagen Timing is perfect. Part of Cython compiled production code just failed for wrong typing as Cython has discipline regarding types. Tests written in Python let it slide.
@@incremental_failure why do people don't stick with a rule on adding the types of stuff into the name of the variables/functions in python? like if it's a integer variable Int_x = 3 def Void_foo(Int_x): String_y = "something" wouldn't that make python usage less... shitty? i dunno cuz i abandoned writting in that mess of slow language and moved to zig and haskell instead. Monads go booooom babyyy
@@PamellaCardoso-pp5tr And complex types? Python isn't that slow either since well, all the complicated stuff has Python only as a layer. If you depend on a dozen or more critical modules, switching languages fast is out of the question.
@@incremental_failure you can try to define interfaces using comments... i dunno man. i would do anything to keep some sort of sanity in my code, specially now that i learned the beauty of types through the category theory point of view and how types relate to each other. and yes, python is slow. you aren't using python, you're using C in disguise, and in that regard Mojo seems to be the thing that will make python less shitty to use, but it will still suck without having damn brackets
Yeah, obvs this only works in languages that are reasonably able to express high-level concepts... unlike notoriously low-level assembly. Some of the techniques suggested don't even work in C because its type system is so simplistic. You don't have to (weirdly) flex that you write assembly.
I always try to comment on why things are done. If running a big chunk it's good for people to know a really quick summary so you don't have to read through it if you are not looking at that particular area.
I like putting a "project philosophy" file into the documantation which gives a general idea of how the projects structure is intended to be. Explaining which services there are, how the code can be extended, etc.
I love when a dev explains what the code is (supposed to be) doing, makes it easier to audit the mistakes if the logic doesn't line up. Someone else being able to tell what your code is actually doing, and it doing what you think it does are two different things.
One point: in embedded programming, sometimes comments are almost necessary. Writing some random number to some random register or similar can be very confusing otherwise. For example: Accessing the DRW register over SWD after setting a new address in the TAR register requires one dummy read first. So, you set the register you want to read from, and then you read twice. Without a comment in there, that seems like a bug. A simple //dummy read after the first read explains what happens.
I agreed right up until the example comment you suggested. Instead of: //dummy read after the first read What you explained right before that suggestion is much better and is exactly the kind of thing you should have in the comment: // Accessing the DRW register over SWD after setting a new address in the TAR register requires one dummy read first. That is just about a perfect comment. I don't know why you'd have such a clear explanation of exactly why you're needing to do something strange, even down to having decent capitalisation and punctuation, and then throw all of that tidiness and information away for a lazy comment that just repeats what the line of code is doing without explaining why.
I agree! I don't write comments that explain code. I write comments if my code is weird or violate a basic principle, like a query inside a loop, that explains why in that particular situation I had no other choice.
I was repurposing an old computer the other week. It is over 10 years old and has code from some of the projects I was doing while learning front-end dev. The comments I wrote in there killed me to read. Practically every block of code had a header like "// ---- Functions ----" or dumb stuff like that XD
I write comments even for code only I will ever see. A year down the road I'll completely forget what a program or script does and what arguments to call it with. I could deduce it from the code but comments make it a lot faster.
Comments need to exist to justify why something was done, so the same mistakes arent retreaded. but comments get stale, because they arent tested or statically checked. so always be careful when writing your comments to not make more assumptions then necessary.
I prefer using test to document behavior. Hence justifying it by making the test fail if changes were made, and hopefully people read the test case name and understood the assignment
I'd say the big exception to this if when you write code to integrate with an external system like a ERP system or something. Having a few comments instead of being forced to spelunk ERP documentation to understand why some seemingly pointless details are included / required saves so much time.
i like to write a comment, or series of comments, to explain to myself how it should work, then build the code to match probably not the best idea, but its helped me learn things
I like the idea of commit message as a comment defining why that line was changed and when, and how it looked before and potentially linking to issue that defines a problem and how it was discovered ....
I like using comments to jot down notes or to organize my thoughts tied to the surrounding code, but as I implement the notes/ideas, those comments get deleted because the code basically becomes the comment
This made me realize that I have a bunch of, what would be considered, redundant code but I don't want to remove it because the human language helps me understand at a glance what the code is meant to do even if that can be surmised by reading the code itself. It also helps with bugfixes if the code doesn't do what the comment says it's supposed to do, the original intent is preserved (though that means I need to update comments when making changes).
I start with piles and piles of comments because my code usually starts out as a steaming pile. The first write is usually a single file in a single night with 4 cups of coffee, with 400 lines of code and 500 lines of comments. Then comes the first refactor, and the second refactor if it's real serious. Now I have well-structured, lightly commented self-documenting code. In the end I try to keep my comments to primarily just refs/links to outside resources like business rules the code is implementing.
I use comments for 2 things: 1. work in progress, so when I come back to it I have an idea of my line of thought and can finish the work 2. To describe an entire script/set of functions, this is so someone doesn't have to read through the file to know the details of what it is accomplishing. This isn't always necessary but I think it is a good habit and really helps people still being on-boarded.
I usually write comments that point to documentation or paste the documentation in there. I work at a payments companies that hook into banks, and they have some backwards ways of writting messages as buffer or hex strings.
Comments are great for “why”, often when I’m in position when I now that solution I posted might seems strange I want to message anyone who ever wants to edit it to double think it why it is that way. Also it is a great marker for fishy code, if something is commented - keep an eye on that one
I wrote protocol specs documentation to talk to firmware in electronic boards i design and build. A client needed to use such boards. I sent protocol specs, he was having hard time. I sent well written, no comments, autoexplicative source code protocol parser class, and he immediately got it. He told me he apparently understands C++ way better than English and/or I can express myself more clearly in C++ than English! That's it: code IS its specs, in the most detailed description possible.
3:35 FIVE_MINUTES = 5 * 60 is awful. Yes, it's better than if (time < 5 * 60) but still awful. If requirement is gonna change from 5 min to 4 min we're supposed to rename const and replace every occurrence? Nah. MINUTE = 60 if (time < 5 * MINUTE) It's perfect balance of readability and flexibility.
Sitting sagely listening to a RUclipsr listening to a RUclipsr talking about what not to do in code (my code has no bugs (because my code does not exist (yet
If comments can lie, then so can function names and variable names. At some point, you have to rely on something unless you want to spend hours minutely examining every line of code just to get your bearings.
yes I rely on functions and variable names, needing comments is a sign that your functions and variable names are trash. People name their variable x then add worthless comments, name your variable velocity or whatever it is you're calculating you stupid monkey.
I remember one of my first programming projects at community college in like 2007. Now, this instructor was like a SUPER nice guy and really square like a Mr. Rodgers or Bob Ross or something. Well I was working on the project and got stuck with something and got SUPER frustrated and put in some VERY profane language in the comments at the time. I thought I had deleted all of them. When I finished it and turned it in, he handed it back to me with errors annotated as well as a comment "please refrain from leaving off colored comments in your code". I turned beet red
i have early projects with comments about what the code is doing, but that's more so I can look at it and go "oh yeah that's how we do that" while still learning
I've seen Primagen confuse borrow checker with allocation & deallocation twice now. Though this time he's somewhat closer to the truth than the last time; because unique_ptrs *does* involve life time management. You can still share a unique_ptr via reference arbitrarily.
3:40 in this scenario, I would argue that you should not name the variable "FIVE_MINUTES" because the variable name can become misleading just as the comment did. If you change 5 to a 3, you might forget to adjust the variable name.
I work in a team where the majority of members have very little coding knowledge, or desire to learn. However, I write a number of Python scripts to support various tasks which occasionally need to be edited/slightly modified by other team members. In this situation are heavy use of comments the way to go? The ideal solution is to upskill the team, but that's never going to happen as the company doesn't hire for coding skills or enthusiasm, and as almost all coding guides (quite rightly) assume you work within a team competent in coding, I feel like they always need heavy adaption to be relevant.
More comments are called for in this situation, especially in sections that you know will be frequently modified, but "heavy" commenting will just be counter-productive in the long run. It'll waste your time and give your coworkers an excuse to avoid reading/doing proper tutorials for coding.
Naming things with the code is better than comments, because the compiler checks you. Actual comments can be plain wrong and you only figure it out after you've been confused. And that's the opposite of what the comment was for!
I think the example at 3:07 is an actual W for the JS community, because if you compare ZIG --> "if (C - 8==D)" VS JS --> "if (C - 8===D)" it actually shows that JS devs have the bigger dick operator..
For me it comes natural. I just put down what I think will be useful to know there. It's like writing notes on paper. I just write stuff that I think will be useful for me in the future. That can come in different forms.
Man what a worth while watch was Tom's Jdsl video. Probably they were the same stream but as someone who just watched clips is funny AF getting a reference to it
ill never stop writing code, i work on so many projects its the only way to keep my sanity, but i use code comments to detail my thought process, why ive done this or that that way, why other ways were not considered or discounted.
Golang got a test suite which validates examples via code and expected output in a comment. These comments are later published in API docs along with the build
I comment what a piece of code is doing all the time, but that's more about me learning and having not the best memory. So I can basically reference my own code like classroom notes
Bunus points, it makes it way harder for a language model to tell what your code is supposed to be doing if there are not comments, or comments that lie.
I work in hardware emulation... the domain essentially requires huge amounts of state and logic in the code to do its job (emulate hardware, which is inherently extremely stateful and extremely combinatorial). We try to manage this as best we can, but you still need that core logic *somewhere*, no amount of abstraction or naming functions will help you here. There's so much external knowledge to the code to make sense of variables and equations that comments are basically necessary to say why XYZ is done at point ABC.
Your specific case is solved by vast documentation about how hardware works, said documentation has some form of naming convention that when followed, helps EVERYONE who read the documentation on how said hardware works to know what is where. Such code requires exactly 0 comments in regards to what is happening. For example gameboy manual references LD opcode, maybe you should name it LD in your code too and then everyone will know about what it means.
i ususaly have lots of comments, because before coding i usually write a pseudo algo of what i need to do so i can organize my thought... and i tend to just leave them
4:18 ehehe, coming from C# I used to be, but since that seems to be the naming convention in the c++ standard library and the language in general, I just adopted it with the argument that consistency is less confusing.
"Fun" fact, 10:40 is valid HTML! Some specific tags, such as and can be closed by a subsequent or , or the closing of the parent, without needing an explicit or . Why? Because HTML, that's why!
In my personal programming language, Symta, all typenames start with a lower-case letter, while all data variables with an upper-case letter. Yeah, I'm a Prolog fan.
I go a step further than not writing comments, I run it through an obfuscator before committing to the repository ♥
Username checks out
@@cmelgarejo how dare you!
It's not often I actually laugh when I "lol" but this was one of those times. Thanks o7
minifying is decent too. who doesnt like variables a..z, aa..zz, etc
I just gitignore the source files and track binaries because at the end of the day, that's what matters most
No wonder Tom didn't add comment support to JDSL. It's self explanatory. Tom is a genius.
This is another reason he should consider using TOML. No comment support.
Fuckin lol 😂 Tom is a genius
Of course, Tom's a genius 😂😂😂
Tom is a genius
@@whig01 TOML is TOM's language?
I blame Scott for not explaining that comments weren't implemented in JDSL.
Scott, the true villain in all of this...
@@ThePrimeTimeagen He was a visionary. A world where you don't need comments to navigate code. He invented JDSL to accomplish this goal, a true Genius.
I agree that senior developers definitely should have made him aware of such a huge vulnerability. I also wonder how something like this was pushed to production. I thought the json metadata was calling for specific revisions of these methods, so you can always maintain backwards compatible dependencies; his changes shouldn't have effected production unless he updated all the metadata to point to his new revisions as well. If he changed so much stuff, why wasn't any of it reviewed? Seems like this company had really bad organizational issues, which allowed for a junior developer to make sweeping changes without oversight.
He should have written a comment in JDSL, explaining that comments are not supported
But unfortunately he could not, since comments weren't supported
He didn't have to implement them, it's a first class feature in the format he selected.
Because he's a genius.
{ "comment": "this is a JSON comment ~Genius Scott" }
The noob that didn't understand JDSL put the comments in the javascript.
The best comment I have ever seen in a code were:
! fiddle with variables and print stuff
It was in a very old Fortran code for doing configuration interaction calculations for atomic nuclei.
respect
@@ThePrimeTimeagen yes, it didn't blow up, respect. bet it was JDSL 😂
A comment that will remain accurate until the heat death of the universe
10/10 would compile again
I once came across "a squid eating dough in a polyethelene bag is fast and bulbous" in a source-provided library.
I suspect I was one of the few dev's reading that code who got the reference.
With the qualifier "most of the time", I absolutely agree. Just yesterday I was cursing my heart out, because code was changed to do the complete opposite of what the comments said. Nobody maintains them, half the time people don't even read them and it takes on average 2 weeks before "redundantly repeating what the code is telling me already" turns into "blatantly lying to my face".
Why don't code reviews catch that? Odd.
"Your comment here is useless. Report to the flogging station immediately."
"This comment has nothing to do with this code. Flogging station."
People would catch on eventually.
@@herrpez I wonder if some of those useless comments can be blamed on certain teachers. I remember at university they told us "for each line of code, there should be one line of comment". You can guess what the result of that was...
This problem arises when people write in comments what the code does instead of what it should do. "Setting timeout to 5" is useless and potentially misleading "waiting till work process completes first cycle" is usefull - even if you change timeout to 15 or replace it with conditinal wait.
Or even if someone "corrects" the code to oblivion - feature maintainer will know what you WANTED to achieve here.
And personally - I just like to mark "difficult" parts of code with prayers to Omnissiah or Cthulhu :)
@@herrpezI guess because people don't look at lines that weren't changed, and if comments stay the same, that means there's nothing to look at
At least that's how my brain works
Maintain them then?
Linus torvalds said it well: Dont describe your code, describe why you are doing something (if it's not obvious).
It's because otherwise the comment does the same thing as the code, so your code should be readable so you dont need comments. But sometimes you need to write code in a specific way for uncontrollable reasons (external issues such as driver issues, some external service behaving in a weird way, some library requiring something that is not obvious, etc).
My favorite is //hackity hack because it removes all doubt that what you’re seeing is bizarre
Sometimes the code is just complicated and needs a comment saying what it does
@@doughxDude87 No. Even if you're doing the most complex computations imaginable, you can explain WHAT the code is doing 2000x better with the actual code itself, rather than some comment saying it in English (just like everything said in the video). Everything said in the video applies to any level of complexity.
@@nerdycatgamer sure there probably is a way to structure the solution to be better. But is it really the worth the time investment to refactor something that can be easily explained with a comment? All depends on the problem and time resources
@@doughxDude87 There is no "refactoring". Write the code correctly in the first place.
If you can make your code readable enough and good enough, don't write comments.
If you can't, Id rather have a commented steaming pile of garbage than a steaming pile of garbage with no comments at all.
Late reply, I know, but what makes you think that someone who can't properly convey their ideas through code would be able to convey said ideas through words?
@@longlostwraith5106sometimes it is that way because you have to work with legacy code and structures. You cant reasonably alter everything so its readable by code only. You dont have enough time and resources to be able to do that a lot ofnthe time.
@@longlostwraith5106 I've seen this and was able to understand what was supposed to happen, delete their code, and fix it. Talking to people and to computers are two different things.
I honestly don't care that comments can lie
I'll take 75% accurate with some context over no comments any day
The real issue is that comments need to be reviewed with the same scrutiny as the code they're describing
^-- this is actually really good observation
I think that comments should be written to summarize rather than to explain. The "write readable code" argument doesn't really work when you still have to read the entire codebase to see what's going on. And it's usually easier to summarize in a few sentences than aLongAndVagueFunctionNameThatsHardToRead.
Yes! I am admittedly very bad at updating comments. But at my last job, part of the review process was making sure your comments are updated. I would pretty consistently be told to update my comments, but the code looked good.
Comments, to me, are incredibly useful, even if they're just directed at yourself. The problem with comments, just like code, is maintaining them, and making sure they stay relavent, just like code!
The problem is not comments. The problem is a review process that does not see comments as useful to review. People just kind of glaze over comments. They should be reviewed just like code.
thankyou. Some sane comment at last
But how do you test comments? Nothing comes to mind as far as having some automated system judge comments. Unless we start using some framework that now reads all comments?
If I can't test it, I'm way less likely to use it in my code. Comments fall under this as well. I hardly use them, save for a very reluctant to-do (don't-do) that I try to immediately get rid of ASAP.
I'll read them, but at some point, I can get away with re-factoring large functions without needing to know precisely what they do.
Real talk: I usually only put comments in code (be it JS, R, Python or SQL) when i am referencing a business rule that needs to be understood. Preferably simply listing the business document link so if code needs to be updated they can go in-depth as to 'why' something is the way it is. I've found this is a big help in research settings where government & sponsor rules and regulations shift ever so slightly quite often.
Extending that, I include references that I used if they were important to figuring out some code.
@@mattmurphy7030 Another extension: Linking to Github Issues when you need a workaround for something that's currently not up to the documentation spec.
This is why BDD test cases exist.
HTML is not fully structural, you do not need to close since they aren't allowed to be nested, the language will auto-close
Rust is the first language where I felt like comments were right. The language is descriptive enough that I dont often need to write comments explaining what's happening. The built in testing system means I don't need to write comments explaining edge cases or intended use. Docstrings with tested examples are probably the best documentation I've ever seen in normal library code.
Obviously other languages can avoid comments too, but in the looser or harder langauges I need comments more.
Go!
Doc strings are just comments
docstrings come from LISP, types as comments comes from ML.
@@KManAbout Doctests will execute the tests in your doc strings. Tests can be nice as you can get chatGPT to implement your function for you from the tests, you could program your IDE to show you values flowing through your program from the tests, you can convert tests into types. However, make sure you are testing the properties of your function as they pertain to your business needs not the implementation details.
I need comments in any environment where i might be 'in the process' of developing a solution to a problem, rather having already solved the whole thing in my head, and I am now just fleshing it out with the obvious and perfectly well behaved and well formed code structure that I have somehow worked out. Or in other words; code is a process. Bad code and bad non-code descriptions need to be possible to represent while you don't have perfect alternatives at hand.
If I didn't have comments, I'd just have documents in my source tree referring to specific spans of coude in the source files that the document is talking about. Essentially, comments with a bunch of stupid extra steps.
I do get the motivation behind this conclusion; you don't want your codebase to be littered with crippled code that needs comment crutches to make any sense. But at some point in the development process, you need to set this aside and write bad code. So you can get around to writing bettter code later.
That only applies to those who are just calling APIs and barely have any advanced logic in their code. When you have advanced mathematics and complex algorithms and equations that are based on geometry, you'll need to explain what are you doing and why and why didn't you go for the other obvious more intuitive way. That's what comments are for. It's not to explain what's happening, it's to tell you why it's happening and what was the developer thinking.
Exactly, well said.
Nailed it. The only real comment in my game is an outline of the pathfinding algorithm. The rest are just “this is here because ___”
He states it himself he's not into math. But math is important for a lot of advanced uses. Scalars, vectors and matrices for example are prominent in a lot of areas where transformations are used. never hurts for a programmer to know how to use advanced algorithms. Who knows, he may realize he can heavily optimize something with it instead of just looping through arrays like a novice. That's fine at the small level, but with large stores of data the processing goes through the roof.
I mostly explain the algorithm in a paragraph inside the function but at the very top of the block. Most of the comments inside the algorithm are just saying what if conditionals mean where it isn’t obvious. The most common example being at the top of an “else”. Like if I have an if block “ if ( size < max ){…” I put “max
good job, you just repeated exactly what the primogen said, including his disclaimer statement
As an embedded engineer, even if your comment is "this code is f'd-up" and at that point, even if it's a lie --- it's still a warning that it is not going to work like what you will work like what is epxected. That's huge. That's helpful. I worked with this stuff that was only very loosely embedded-to-JS, and copying it immediately via clone seemed silly --- but the comment saying, "this is f'd-up, I get it"... GOOD STUFF.
I'm a beginner, this kind of videos frustrated me a lot because of the titles "don't write comments", "don't do this", "dont do that"...
And, a beginner life is like:
-> Starts to learn about comments
-> Start learning how to comment well
-> Start commenting well
=-=-= 1 Week Later =-=-=
*RUclips video telling you to not write comments*
Beginner Conclusion: All you've learned is wrong.
=-=-= Sometime Later =-=-=
-> Starts to learn about OOP
-> Got used to OOP
-> Start writing good OOP code
=-=-= 1 Week Later =-=-=
*RUclips video: "OOP IS WRONG", "OOP IS THE ROOT OF ALL EVIL"*
Beginner Conclusion: All you've learned is wrong.
And this applies for all of the things I've done. ALWAYS, sometime later, a video will show trying to discourage me or prove that what I'm learning is wrong and it shoudn't exist.
I bet if I start learning Rust, 1 week later, a video will show to me telling that Rust is "bad".
But I don't fall for this anymore. I learn by myself now.
Yeah, that’s because nothing is 100% the absolutely correct thing to do. There are debates and tradeoffs to most things. Writing good comments is good, writing bad comments is bad. Using OO can be good for modeling, using OO can have bad results for program structure and performance.
Just accept that nothing you’re learning is the absolute end-all-be-all and understand you will eventually learn a flip side to what you’re doing.
Eventually you’ll know enough that you’ll have your own opinions and you won’t worry too much about what some guy on RUclips says. Like this video, you’ll hear the useful parts and shake your head at the dumb parts.
You’re ahead of the curve realizing that anyone claiming to have THE answer is going to be contradicted later. Every new framework and paradigm that gets introduced as god’s own work is eventually replaced.
The problem solving and learning skills you build are what matters. The tools always change.
@@mattmurphy7030 Totally agree! Thanks 👑
While I'm not a beginner, I recently started getting back into coding after several years away and I feel this from videos I've seen.
My method has just been, 'appreciate what's being discussed, and then continue doing what you're doing, perhaps applying this new information to it'.
In my current code for example, I'm commenting _every_ function, specifically so that I have reminders as I warm back up to coding. Once I'm more on a role, I'll feel more confident removing comments or narrowing them down to just pointing out why sections appear weird.
Good man, the takeaway lesson is to take onboard someone’s claim or opinion, but don’t believe anything until you’ve tested and confirmed for yourself. It can take a long time to do this so don’t try and pick a side until you’re satisfied with your understanding. Someone says comment intent, someone says don’t and make code clear to understand, maybe a one-size-fits-all is actually never the answer and the fact is it will always depend on situation and circumstances, keep doing more of what works best for you and do less of what doesn’t. It’s like mastering any skill, masters never stop honing their craft, don’t look for a finish line, rather enjoy the journey and recognise that when you hear opinions or blanket statements like this that one day you will have found your own foundations from experience that will no longer be shaken by others. Your journey will be yours and nobody else can tell you the right way to go, because nobody else can take your path except you.
☮️ ✌️ 💻 ❤
@@mattmurphy7030Good advice 10/10
Sometimes you have to use libraries that have such convoluted interfaces and unintuitive names your code will become unreadable just due to that. In some languages that includes the standard library..
And having to read documentation won't help you, the problem is bad variables and functions, not lack of comments.
All these guys have a good idea, and then try to apply it to all situations everywhere.
Sometimes you need a comment, so write a damn comment.
50 year veteran here. If you have ever come across code you wrote 30 years before and thought "WTF was I doing this for?" because you know you had a really good reason but you can't remember what it was, then you know why comments are crucial. As a team lead I would refuse to OK code that doesn't tell me what a piece of code is supposed to do without having to read the code. It should also tell me the reasoning if anything is "non obvious".
Lets say, hypothetically, if there was a way to somehow let people know how the piece of code works without writing comments. I mean, what if there was a document, somewhere in confluence, that told specifically how the code works, which type of response to wait for. I can't think of something like that existing.
@@assetaden6662I believe that is called rotting documentation
I think using comments as headers to segment areas of a large code blocks, is something useful. It allows quickly skimming through code, without having to read the whole thing.
I will admit, I do sometimes do this. But this typically indicates that your function is doing too many things and should be split.
If you have to write headers to segment your code, you either have functions that are much too l large or your file is way too large.
why not moving the sections into their own functions?
@@Yotanido if it's a bunch of things you only have to do once with no repetition, splitting it up is likely a waste of time.
@@ScibbieGames if you have such a big thing that you need to write segment comments, usually you could instead use the time to comment it to just split it into different files/classes in the first place and then wouldnt need the comment any more.
This guy’s voice is awesome. Like, I never thought I’d be able to tolerate a voice like this but he’s even more hilarious because of it. I can’t get enough of his videos.
It's because he sounds like a cartoon character.
@@stefanms8803 this is exactly it
Here to the clean code camp who say the code should document itself: This is what your function names end up look like:
- setupPageSizeA
- navigateToSectionFourteenParagraphThirtyTo
- handleTopLeftCornerButtonClickWhenUserIsUpsetAndFrustrated
... The names are so meaningful that you don't need to write comment at all. And Shakespeare shall be proud of ya.
Lmao you're retarded, in reality what you wrote looks like this:
setup_page(page_size::A4)
navigate_to(section(14), paragraph(32))
on_feedback_form_button(callback parameters...)
And yes it's perfectly readable and you're a braindead moron, your forced use of camelCase is proof enough but your attempt at naming is just as bad.
this is hyperbole. You can easily create concise names that clue in to what the code is doing. you just sound like youre bad at naming.
Names should be clear and concise to function. Comments should be added when that isn't sufficient. It's not hard.
Is this video made by Tom the Genius?
Tom the gineous is such a genious
@@ThePrimeTimeagenwow thats really geanious
Just watching this channel the last year made me a better programmer. Love you Prime, thank you
I love how "Tom" the megamind genius is a recurring character in these stream highlights
I love how he's so ingrained that Prime's ADHD tourette outburst names him.
tom is the creator of TOML
@@parthpandey2030Yep, a Tom made the language, but not _that_ Tom
Comment now perfect later. Comments are context.
Beginners need context and have to learn to communicate it.
Technical writers need context to document.
Senior devs create context and have to clarify it.
Managers and stakeholders need explanations from everyone else depending on that context.
The idea of not commenting is arguing for a perfect ideal code that will never exists.
Just comment.
You know there were these kinds of exceptions listed in the video, right? You actually watched it, and didn't just comment after reading only the title, right?
The math in his if statement example had me laughing 😂. And he did it so smoothly, that it doesn’t come off as inappropriate.
Nothing to add here, just let me state a fact...
Tom is a Genius.
Oh is this gonna become a thing? I'm down.
@@jaredmistretta3018 Hi down, I'm up.
the comments should be about the design rational, the trade offs, business requirements and context. If you're writing a library that calls some other service, the comments should be about the quirks of the service and any odd stuff that you found. The comment should be about "how do I help someone maintain the code."
Me writing comments for my future self has saved me, sometimes just the why, sometimes some what's to make a piece less dense (sometimes I write dense code when I'm in a flow, but I won't be in that same mindset a year later).
The best thing to do is to write comments to someone out of the loop just to bring them to speed.
Put it where it matters, so if that specific thing changes, so does the adjacent note/comment.
Those that don't give themselves/others future notes have not ran into that issue.
After they have the experience of going into different projects and having to revisit the past and realize they can't put together what they thought was obvious, they have to read a bunch of code to catch up to that mindset for that moment, then they'll have wised up to what to put, where to put it, and smart enough to keep those important bits up to date.
At my job we often end up going over the code in a pair of reviewer and author. If at any point we need to stop at a piece of code to explain why it's the way it is or we stop because even the author needs to think about it it's always a three step process
1) what does the code do exactly?
2) Can it be simplified or cleaned up?
3) If no, put a commend explaining why the code is the way it is
It's a rare occourence, oftentimes to adapt some weirdness from a third party library or incomming data. But when it happens the comments do actually help.
Basically: If you read a line of code and your first thought is "WTF is this?". It's probably time for a comment
I am a fan of triple-slash comments in C#, my thought is that if you need a comment inline, it probably should be it’s own function and then inside the triple-slash I can detail what is being done, what are the concerns for the comments, and why did I decide to do this. It also allows me to explain concepts.
It also can be used by auto-documentation tools to make documentation. And then there is a team effort to update and scrutinize the comments when we change things up such that people can better understand.
Self-commenting code has been a nightmare to work with in the past, because evaluating decisions for refactors suck.
++ comments for methods are truly helping, and every library should use it. If a method doesnt have this intellisense comment, i always get a little angry.
Honestly C#'s /// comments are less like comments, and more like in-source documentation. Heck, they evem appear in your tooltips!
These are called "doc comments", and I think that they originated in Java, which is a language that, like C#, I don't want to use for anything if I can help it, but the doc comments are a good idea, which is why Rust has them as well.
3:04 Human hability of choosing some two random values: 77 and 69.
7:01 C++11 optionals comes from boost::optional (introduced in boost in 2004). If you mean the origin of optional has a "programming idea", not sure, but it's an idea that comes very naturally. It's very likely that a lot of companies and even personal projects have introduced some kind of "optional" type from themselves years before boost.
Software Engineer speaking: I will ensure anyone who doesn't use/maintain clear and concise code comments will be assigned as far away from a keyboard as possible.
ah yes, the software engineer who can't even read real code but has power to tell me how my code should be written is speaking...
@@shinobuoshino5066 Yeah no, I've seen enough piss poor code written by EE's moonlighting as proper Software Engineers where I am tired of wasting time and effort trying to decipher what the hell you were attempting to accomplish.
If you can't clearly document your code, I will ensure you never touch a keyboard again.
My first computer science teacher made us write out what our functions were going to do before we could code.
We also had to put in the comments which function was calling which.
It is actually easier to run my code through an anti comment program (just deletes any thing in a ‘’’ or after #) than to break this habit unfortunately.
Lmao, imagine seriously requiring to put in comments what function is being called, when the function body already shows all functions being called...
@@shinobuoshino5066 I know this might seem stupid. But they wouldn't even let us use IDE's. The teacher was from a country where they were programming using Notepad++ as the IDE.
Imagine all of this and then on top of it, they exclusively taught OOP in Java at the time, too.
Safe to say, a lot of ppl were scared away from CS by this entire experience.
10:40 - Not all HTML tags require closing tags, and I'm not referring to self closing tags like . It goes back to the early days of the web, when you wanted to send as few bytes as possible over the wire. The HTML spec allows you to omit closing tags in some cases as the other rules in the spec prevent ambiguity. If you don't follow the spec of course, all bets are off. I saw some of your chat saying it's a new thing, this is false. It's always been the case.
Maybe it’s just because I mainly do embedded programming, microcontrollers, FPGAs and similar, but comments are very useful sometimes and I would rather commented code than non commented code, if the comments don’t make sense you can always fall back to just reading the code.
Probably the more complex your domain the more comments can be helpful.
I had a number of issues with the original video when I first saw it. It's basically "bad comments are bad" behind a misleading title. The example at 7:48 just deepens that tautology. Yes, absolutely 100% construct your code to do everything you can to not need comments. But yeah, absolutely write a comment if you're doing something weird or if some context will help someone else out or speed things up. Basically, just try to put yourself in someone else's shoes and ask, "Would someone else immediately know what the hell I'm trying to do with this or would this seem pretty cryptic?" The thing may be obvious to you after 3 months mucking around in the codebase but is a newly onboarded junior engineer going to be baffled? At worst, a stupid comment like the one at 7:48 is going to be disregarded when it's recognized as out-of-date. "Don't throw the baby out with the bathwater" blah, blah blah.
Blah blah blah to you. Thr original video is good. And it's not dogmatic in it's position.
I find comments that explain the code useful in two circumstances:
1. As a block comment at the top of a file, summarizing what the file does
2. Comments breaking up sections of a large procedural function that does several complicated steps.
Many people will say "if you have several complicated steps, you should just split them into multiple named functions". But I disagree with this. When you split them into functions, you're implicitly saying "these functions can be called Independently, and perhaps in any order". But in the case of the large procedural function, each step must happen in a very specific order, and the steps shouldn't be invoked in isolation. Having them in order within a single encapsulated function is much better for expressing how it should be actually used, and comments can just help summarize what each complicated step is doing, and provides a little break between reading each section.
Wait... even if you're using C, you can still introduce a block. Declare variables that later portions need before the block, then have a block of statements that do some related work and initialize your variables, and boom: a section without comments. Repeat until your big function has enough sections to be comprehensible. Maybe the variables from each block will say why the block exists... or else you add a "why" comment, so #2 is just a special case of #1.
@@okuno54 yeah, sometimes you don't need comments in each section. Sometimes you do, because the variables don't explain it well enough. I use blocks in C all the time
I've been struggling with a relatively short function as of late regarding datetime conversion and various adjustments with a dynamic axis. The code is commented a lot and it has taken me over a week to understand it. Functions and classes are intertwined, most variables are kept short for whatever reason, lists and dicts are unpacked into objects, functions are passed in init, of course no type hints (yes, it's python). A simple thing like using longer, easier to follow variable names would solve so much and dynamic typing is the absolute worst thing about python.
me hates dynamic typing
@@ThePrimeTimeagen Timing is perfect. Part of Cython compiled production code just failed for wrong typing as Cython has discipline regarding types. Tests written in Python let it slide.
@@incremental_failure why do people don't stick with a rule on adding the types of stuff into the name of the variables/functions in python?
like if it's a integer variable
Int_x = 3
def Void_foo(Int_x):
String_y = "something"
wouldn't that make python usage less... shitty? i dunno cuz i abandoned writting in that mess of slow language and moved to zig and haskell instead.
Monads go booooom babyyy
@@PamellaCardoso-pp5tr And complex types? Python isn't that slow either since well, all the complicated stuff has Python only as a layer. If you depend on a dozen or more critical modules, switching languages fast is out of the question.
@@incremental_failure you can try to define interfaces using comments... i dunno man. i would do anything to keep some sort of sanity in my code, specially now that i learned the beauty of types through the category theory point of view and how types relate to each other.
and yes, python is slow. you aren't using python, you're using C in disguise, and in that regard Mojo seems to be the thing that will make python less shitty to use, but it will still suck without having damn brackets
"The compiler does not read comments, and neither do I."
- Bjarne Stroustrup
My rule for writing comments is that comments should describe why the code is there, not what it does.
Thats why Tom said f u to comments in his JDSL , Tom is a genius
time and time again, tom is a genius
"Don't write comments"
5 minutes later: "volatile asm(..."
Very nice, agree in most points.
Now, try to write an assembly code with no comments and come back 6 months later
That’s cheating
Yeah, obvs this only works in languages that are reasonably able to express high-level concepts... unlike notoriously low-level assembly.
Some of the techniques suggested don't even work in C because its type system is so simplistic. You don't have to (weirdly) flex that you write assembly.
I always try to comment on why things are done. If running a big chunk it's good for people to know a really quick summary so you don't have to read through it if you are not looking at that particular area.
I like putting a "project philosophy" file into the documantation which gives a general idea of how the projects structure is intended to be. Explaining which services there are, how the code can be extended, etc.
The most common use I've found for comments is commenting out code during debugging
I love when a dev explains what the code is (supposed to be) doing, makes it easier to audit the mistakes if the logic doesn't line up.
Someone else being able to tell what your code is actually doing, and it doing what you think it does are two different things.
Also not everyone thinks in the same way. Something may be so simple and obvious to you, but make no sense to another debeloper.
One point: in embedded programming, sometimes comments are almost necessary. Writing some random number to some random register or similar can be very confusing otherwise.
For example: Accessing the DRW register over SWD after setting a new address in the TAR register requires one dummy read first. So, you set the register you want to read from, and then you read twice. Without a comment in there, that seems like a bug. A simple //dummy read after the first read explains what happens.
I agreed right up until the example comment you suggested. Instead of:
//dummy read after the first read
What you explained right before that suggestion is much better and is exactly the kind of thing you should have in the comment:
// Accessing the DRW register over SWD after setting a new address in the TAR register requires one dummy read first.
That is just about a perfect comment.
I don't know why you'd have such a clear explanation of exactly why you're needing to do something strange, even down to having decent capitalisation and punctuation, and then throw all of that tidiness and information away for a lazy comment that just repeats what the line of code is doing without explaining why.
I agree! I don't write comments that explain code. I write comments if my code is weird or violate a basic principle, like a query inside a loop, that explains why in that particular situation I had no other choice.
I worked for a company once were we had a new junior hire that quit the first day, citing the lack of comments as the number one reason
I was repurposing an old computer the other week. It is over 10 years old and has code from some of the projects I was doing while learning front-end dev. The comments I wrote in there killed me to read. Practically every block of code had a header like "// ---- Functions ----" or dumb stuff like that XD
Almost as bad as //increment the index
damn u didn't have to call me out like that
I write comments even for code only I will ever see. A year down the road I'll completely forget what a program or script does and what arguments to call it with. I could deduce it from the code but comments make it a lot faster.
Agreed. I do the same. And, if the person doesn't like comments they can just ignore it
Comments need to exist to justify why something was done, so the same mistakes arent retreaded.
but comments get stale, because they arent tested or statically checked. so always be careful when writing your comments to not make more assumptions then necessary.
I prefer using test to document behavior.
Hence justifying it by making the test fail if changes were made, and hopefully people read the test case name and understood the assignment
I'd say the big exception to this if when you write code to integrate with an external system like a ERP system or something. Having a few comments instead of being forced to spelunk ERP documentation to understand why some seemingly pointless details are included / required saves so much time.
you feel forced to comment old/legacy code to hopefully guide the next sucker to greener pastures, also python is epic
i like to write a comment, or series of comments, to explain to myself how it should work, then build the code to match
probably not the best idea, but its helped me learn things
Comments are meant to document intention. A well-placed paragraph can obviate the need to read and understand hundreds of lines of code.
I like the idea of commit message as a comment defining why that line was changed and when, and how it looked before and potentially linking to issue that defines a problem and how it was discovered ....
I like using comments to jot down notes or to organize my thoughts tied to the surrounding code, but as I implement the notes/ideas, those comments get deleted because the code basically becomes the comment
I write comments to describe why something needed to be done a specific way
I’m 40k lines into a game and so far the only real comment I’ve felt compelled to write is an outline of the pathfinding algorithm
I will only ask for comments to answer "why" but not "what". But having "why" comments saves people time later when needing to make changes.
This made me realize that I have a bunch of, what would be considered, redundant code but I don't want to remove it because the human language helps me understand at a glance what the code is meant to do even if that can be surmised by reading the code itself. It also helps with bugfixes if the code doesn't do what the comment says it's supposed to do, the original intent is preserved (though that means I need to update comments when making changes).
I start with piles and piles of comments because my code usually starts out as a steaming pile. The first write is usually a single file in a single night with 4 cups of coffee, with 400 lines of code and 500 lines of comments. Then comes the first refactor, and the second refactor if it's real serious. Now I have well-structured, lightly commented self-documenting code. In the end I try to keep my comments to primarily just refs/links to outside resources like business rules the code is implementing.
I use comments for 2 things:
1. work in progress, so when I come back to it I have an idea of my line of thought and can finish the work
2. To describe an entire script/set of functions, this is so someone doesn't have to read through the file to know the details of what it is accomplishing. This isn't always necessary but I think it is a good habit and really helps people still being on-boarded.
I usually write comments that point to documentation or paste the documentation in there. I work at a payments companies that hook into banks, and they have some backwards ways of writting messages as buffer or hex strings.
Prime, I gotta say, you react in the best way possible. Your commentary and support for the creator are top notch.
Comments are great for “why”, often when I’m in position when I now that solution I posted might seems strange I want to message anyone who ever wants to edit it to double think it why it is that way. Also it is a great marker for fishy code, if something is commented - keep an eye on that one
I wrote protocol specs documentation to talk to firmware in electronic boards i design and build. A client needed to use such boards. I sent protocol specs, he was having hard time. I sent well written, no comments, autoexplicative source code protocol parser class, and he immediately got it. He told me he apparently understands C++ way better than English and/or I can express myself more clearly in C++ than English!
That's it: code IS its specs, in the most detailed description possible.
3:35 FIVE_MINUTES = 5 * 60 is awful.
Yes, it's better than
if (time < 5 * 60)
but still awful. If requirement is gonna change from 5 min to 4 min we're supposed to rename const and replace every occurrence?
Nah.
MINUTE = 60
if (time < 5 * MINUTE)
It's perfect balance of readability and flexibility.
Watching ThePrimeagen instead of sitting down and coding is the real copium
Sitting sagely listening to a RUclipsr listening to a RUclipsr talking about what not to do in code (my code has no bugs (because my code does not exist (yet
If comments can lie, then so can function names and variable names. At some point, you have to rely on something unless you want to spend hours minutely examining every line of code just to get your bearings.
yes I rely on functions and variable names, needing comments is a sign that your functions and variable names are trash.
People name their variable x then add worthless comments, name your variable velocity or whatever it is you're calculating you stupid monkey.
I remember one of my first programming projects at community college in like 2007. Now, this instructor was like a SUPER nice guy and really square like a Mr. Rodgers or Bob Ross or something. Well I was working on the project and got stuck with something and got SUPER frustrated and put in some VERY profane language in the comments at the time. I thought I had deleted all of them. When I finished it and turned it in, he handed it back to me with errors annotated as well as a comment "please refrain from leaving off colored comments in your code". I turned beet red
i have early projects with comments about what the code is doing, but that's more so I can look at it and go "oh yeah that's how we do that" while still learning
I've seen Primagen confuse borrow checker with allocation & deallocation twice now. Though this time he's somewhat closer to the truth than the last time; because unique_ptrs *does* involve life time management. You can still share a unique_ptr via reference arbitrarily.
3:40 in this scenario, I would argue that you should not name the variable "FIVE_MINUTES" because the variable name can become misleading just as the comment did. If you change 5 to a 3, you might forget to adjust the variable name.
Can you stop redundantly naming constants based on their expected value for FIVE MINUTES!?
moving the condition to it's own function seems like best practice for me
I work in a team where the majority of members have very little coding knowledge, or desire to learn.
However, I write a number of Python scripts to support various tasks which occasionally need to be edited/slightly modified by other team members. In this situation are heavy use of comments the way to go?
The ideal solution is to upskill the team, but that's never going to happen as the company doesn't hire for coding skills or enthusiasm, and as almost all coding guides (quite rightly) assume you work within a team competent in coding, I feel like they always need heavy adaption to be relevant.
More comments are called for in this situation, especially in sections that you know will be frequently modified, but "heavy" commenting will just be counter-productive in the long run. It'll waste your time and give your coworkers an excuse to avoid reading/doing proper tutorials for coding.
This is one of those situations where comment is justified. Hence "comment is bad **most of the time**" not "all of the time"
Naming things with the code is better than comments, because the compiler checks you. Actual comments can be plain wrong and you only figure it out after you've been confused. And that's the opposite of what the comment was for!
I think the example at 3:07 is an actual W for the JS community, because if you compare
ZIG --> "if (C - 8==D)" VS JS --> "if (C - 8===D)"
it actually shows that JS devs have the bigger dick operator..
For me it comes natural. I just put down what I think will be useful to know there. It's like writing notes on paper. I just write stuff that I think will be useful for me in the future. That can come in different forms.
Haskell had optionals around 1995 so probably before then
SML(1983) also has , i dont find if ML(1973) has
Man what a worth while watch was Tom's Jdsl video. Probably they were the same stream but as someone who just watched clips is funny AF getting a reference to it
ill never stop writing code, i work on so many projects its the only way to keep my sanity, but i use code comments to detail my thought process, why ive done this or that that way, why other ways were not considered or discounted.
Long live Tom. Tom is a genius!
Golang got a test suite which validates examples via code and expected output in a comment.
These comments are later published in API docs along with the build
you should know that Tom writes comments to comment other comments. that's why he's a genius
The ‘I use zig by the way’ at the beginning gave me the chills of ‘I use arch by the way’
I love it that in the first 43 seconds you already had 4 pauses :D
ThePauseagen
I comment what a piece of code is doing all the time, but that's more about me learning and having not the best memory. So I can basically reference my own code like classroom notes
Code describes "how", reading it describes "what", comments describe "why"
Waiting for the Tom's a genius merch. There's your startup.
Bunus points, it makes it way harder for a language model to tell what your code is supposed to be doing if there are not comments, or comments that lie.
I see myself all the time cleaning my phone screen due to some little black spot,but it's always the microphone green screen
In Rust, code examples in comments also function as Tests, which is a great feature.
I work in hardware emulation... the domain essentially requires huge amounts of state and logic in the code to do its job (emulate hardware, which is inherently extremely stateful and extremely combinatorial). We try to manage this as best we can, but you still need that core logic *somewhere*, no amount of abstraction or naming functions will help you here. There's so much external knowledge to the code to make sense of variables and equations that comments are basically necessary to say why XYZ is done at point ABC.
Your specific case is solved by vast documentation about how hardware works, said documentation has some form of naming convention that when followed, helps EVERYONE who read the documentation on how said hardware works to know what is where. Such code requires exactly 0 comments in regards to what is happening.
For example gameboy manual references LD opcode, maybe you should name it LD in your code too and then everyone will know about what it means.
i ususaly have lots of comments, because before coding i usually write a pseudo algo of what i need to do so i can organize my thought... and i tend to just leave them
4:18 ehehe, coming from C# I used to be, but since that seems to be the naming convention in the c++ standard library and the language in general, I just adopted it with the argument that consistency is less confusing.
"Fun" fact, 10:40 is valid HTML! Some specific tags, such as and can be closed by a subsequent or , or the closing of the parent, without needing an explicit or . Why? Because HTML, that's why!
In my personal programming language, Symta, all typenames start with a lower-case letter, while all data variables with an upper-case letter. Yeah, I'm a Prolog fan.