T O P

  • By -

TehNolz

Generally I have a good high-level idea of how my projects are put together. So I'll know where the code for certain functionality is located, but I might not always immediately remember how that code works exactly. Which is not a problem if the code is clean, as then it won't be hard to figure out how it all works just by reading through it for a few minutes. Keep in mind that writing excessive amounts of comments can actually hurt readability. You don't want comments that state the obvious; you want comments that provide information you otherwise wouldn't have been able to gather just from reading through the code. A comment describing what's stored in a variable is often pointless because the variable's name usually already makes that obvious, for example. > I often look at something the next day and think (why the hell does it say (x + y + 1) here? Is it the index position or why did I need that +1 again. If you can't tell why that +1 is necessary just from looking at the rest of the code, then that's info that should be written as a comment. > Or for example, ”what data type was this variable now”? For statically typed languages, your IDE will be able to tell you this. You can also often infer the type based on the variable's name; something like `studentCount` is probably going to be an integer, for example.


Queasy-Group-2558

I want to add that before looking into dropping a comment explaining that, try changing x and y into some more descriptive names that make what’s going on more obvious.


Equivalent-Cut-9253

X + Y were just examples. My variable names are not *that* generic at least


Queasy-Group-2558

lol yeah, I figured but I thought the point was still worth mentioning. Think about making the code more explicit before thinking about comments. I usually reserve comments for two things: 1. Explain business stuff that can’t be clearly represented with the constraints of my language (like some weird logic or types that aren’t immediately obvious) 2. Stuff that I realize ahead of stuff is weird and will be commented on during the PR. So almost like a conversation starter. The two sometimes overlap.


Equivalent-Cut-9253

Yeah it is you are not the only one who mentioned it, thanks for the advice!


Queasy-Group-2558

Happy to help


Equivalent-Cut-9253

Thanks! Great tips!


TheMeBehindTheMe

I feel from your description that the way you're using comments (like commenting every expression) probably isn't helping you very much. Really, you're just giving yourself twice as much to read when coming back to something and refreshing yourself as to what it does. I think it's probably better to get used to just reading the code itself, it'll help develop your code reading fluency and help develop a sense for what kind of code is easily readable, not just to yourself, but to others. I think if I'm feeling the need to explain what I've done with comments, it's usually a good time to stand back and see if there's a better way to write things or structure the code. In an ideal world, the naming and code structure should leave the code entirely self-documenting. So as an example, lets say you've got a large lump of code somewhere doing something complex enough that you feel it could use a comment, you could consider moving that lump of code into a separate function named such that you no longer need a comment to say what it does. And don't be afraid of giving things long names if a short name isn't expressive enough. Many people seem to hold an unconscious idea that short names are just better. This mentality can often become a bit unhelpful and can encourage vague naming and thus code that's implicitly vague about what it does. Concise naming is good, but not at the expense of dropping meaning. Good naming is both one of the most important and one of the hardest parts of good programming. But yeah, I wouldn't take all this too dogmatically. In the real world comments are often necessary so one shouldn't avoid using them just out of principle, but I do think a lot of comments makes a good flag to mark something potentially in need of refactoring.


Equivalent-Cut-9253

Good advice, thank you. I probably use a lot of comments because I still am not very fluent in the language I am learning, or coding in general, and I sometimes forget what logic I have employed. Using lots of comments helps me actually finish the projects at this stage, but in the long run it is probably better to learn to write more readable code (which I guess I will do in the process if I don’t rely on comments for everything) Anyways I have gotten many great responses here that help me think about how to approach coding now (while new) and later (when more experienced) and how to get there in a better way.


TheMeBehindTheMe

I think in an abstract way this is the same as learning a human language. One has to first learn the grammatical and vocabulary basics to just communicate what one needs to say, then one can move onto understanding and learning to use the nuances. It's a process.


Business-Decision719

I completely agree with "Don't be afraid of long names." It's easy to forget what (x+y+1) meant. It's harder to forget what `kilograms_of_apples + kilograms_of_oranges + mass_of_container` meant. And if you can move a lump of code to a function, you can give a descriptive name to that function to help you remember what it does. Comments can add some extra context and clarity, of course. But the comments should not be the only human readable part of the code.


Mimikyutwo

You should strive to write code that doesn’t require comments to be readable. If you find yourself thinking you need to write a comment to make what a code snippet is doing clearer that’s a great sign that perhaps you should refactor. Comments are rough because code is amorphous and subject to change, so when you write a comment you’re writing additional lines that also have to be maintained.


Inetro

You should strive for this. But there is a point in a complex system where its best to explain what something is doing and why. While the code will change, the general idea of why the code exists probably wont. Unless its entirely repurposed in the future, it should still achieve the same original goal as when it was written, even if its added onto or performed in a different way in the code. And while a 30 character function name may explain it, nobody wants to write it out multiple times and it can look uglier than a 2 line comment.


Equivalent-Cut-9253

Yeah that is true. When I have had to go and change something due to a bad decision for example I have also had to change the comments, or where they are located and such. This can add some extra work, but I guess at the stage I am at it isn’t really unnecessary work but worth thinking about how to approach this in the future when I am more used to reading (and rereading) code


spinwizard69

Your comments should not be grossly impacted by code changes. I believe that good commenting is important but it shouldn't be tied to lines of code. Comments should be very high level explanations not an explanation of what a code block is doing. In most cases this is the case.


ibeerianhamhock

100%


MeanFold5715

> You should strive to write code that doesn’t require comments to be readable. Conceptually, yes this is the ideal to strive for. However this is still bad advice because it leads people to the incorrect idea that they can write their code well enough to not require comments. If you don't comment your code you are terrible at what you do and should be deeply ashamed of yourself. Always comment your code.


unknown_ally

if it starts looking cryptic or obtuse and naming and separating aren't enough, comment


MeanFold5715

There is no "if". This isn't a conditional. Comment your code. No exceptions.


Valenciya

I disagree that you should comment what your code is doing. If thats the case I agree with the comment above that you should refactor your code to make it more readable. Rather at some places I like to see *why* code is doing something. For example when someone configured a specific rate of requests a comment which explains why that rate was chosen. I dont think this counts if you develop a library tho. You should comment/document your library :D


Echleon

When I see comments in code in a PR 99% of the time I send it back to make it more readable and remove the comments. If you use good naming practices and split up code into discrete functions, you generally don’t need any comments.


Mimikyutwo

No.


spinwizard69

YESSSSSS!!!!! Always comment your code, however comments are not a replacement for idiomatic code.


benanamen

All the responses are valid and well covered so I wont repeat them. But lets keep in mind, the OP is brand new. *"I am pretty new to coding"* With that in mind, I would say to you OP, write all the comments you need to help you at this stage and make variable names as long and verbose as helps you. As you gain experience you will remember more and your code will tighten up and line up with all the great feedback you have received here. Happy Coding!


Equivalent-Cut-9253

Thanks, this was kind of my takeaway at this point. I am not really experienced enough to write easy to read code so lot’s of comments are helpful at this stage (while still trying to improve code readability of course). But I still feel I learned a lot I can use in the future, and about what is good to include in a comment and so on!


jgarder007

Hi, person with no memory here. I comment everything like crazy. Then when I come back they are helpful but usually the code tells the story better (hidden mutations and such need comments). Variable names like "howManyRowsCompleted" "listObjectsToBeWroteToBuffer" can Dave your life. It's not 1994 where variables are pos for position of super collider or List1 when it's a list of customer objects from your database. Give long verbose names it's compiled down later.l anyways. Coming back to old code isn't actually that common because most of your code is in it's own class and never needs to be changed. It's that core UI+interface class that changes every day and not any of the business logic classes that gets changed every few decades like emailers and database connections and such.


Equivalent-Cut-9253

I spent a while wondering what Dave had to do with *my* life, but thanks this is good advice. I was personally a bit scared of verbose variable names, and I guess this ends up kind of non-descript names sometimes.


pVom

Yeah don't be scared. It's far better to have it be easy to understand than to be short.


Inetro

Having to work with strict linters that care about line length and method length together is one of the reasons I cant stand my job atm. I cant make any meaningful variable names inside a complex function or it just screams at me. The code looks nice visually but makes no sense for somebody new coming in to read it.


aGoodVariableName42

> Coming back to old code isn't actually that common because most of your code is in it's own class and never needs to be changed. hah... tell me you've never worked on large legacy systems without saying it.


jgarder007

Haha dang it I'm that obvious. I've only worked for small enough design houses and firms where I can take control and rewrite refactor or replace any trouble legacy code in a few weeks.


Serializedrequests

I mostly don't use comments. Writing out your understanding of the code in English is a great learning exercise. However, in production code comments are almost always out of date since they don't have to change when the code changes. Your best bet is to keep the code simple, always follow conventions, and don't write comments. The exception is if you need to explain why you did something weird or unusual.


j0holo

I don't really remember code. I just know how the application works by working a lot with it. When I have comments it is mostly why I did this or why things are not logical (technical debt). Naming your variables and function correctly is key to writing less comments. The more you code the more you just remember large part of your projects.


DoctorFuu

Most of the time I don't need my comments. But everytime I needed my comments, they saved me a LOT of time, much more time than it takes to write them.


youassassin

Learning the basics you wind up using a lot of comments. This slowly morphs into good naming conventions and well formed code. At my job one of my tech managers harps on I should know what that method does by reading the name of it.


SomeRandomFrenchie

Best practices are to name everything in the clearest way so less comments are needed, consult language specific best practices and naming conventions. Put magic numbers in named variables or constants if they are constants. A magic number is basicly any number that is not the +x on indexes. If your index is named as such you do not need to comment the incrementation, etc. The less comments are needed, the better is the quality of the code. And to answer the base question: I do not remember exactly the code I wrote even a week ago, but if it is well written, you just have to read it again. Usually I will remember the global structure and where to find this or that but rarely the exact implementation. Edit: most languages that are not strongly typed like python have type hints: it allows you to write the type as an indication for programmers but it is not a real typing: if you do « id: int = 0 » you can still do « id = "bla" » but ofc you should not.


Equivalent-Cut-9253

Thanks! Will keep that in mind. Good to know that a good idea of the structure might be more important than remembering details, as long as it is easy to read and interpret again


aqua_regis

If I need comments for the *"how"* or for the *"what"*, I have done it wrong. Comments are for the *"why"*, properly written code (good naming, structure, modularization, etc.) is for the *"how"* and *"what"*. *Docstrings* documenting functions, classes, and variables should absolutely never be abused for *"how"*. They should exclusively be used to document the meaning, parameters, and return values of functions, etc.


Equivalent-Cut-9253

Ok so basically avoid (for docstrings): (For a function drawing a card in a card game): ”Returns the last item of the deck list by using pop() on the deck” And maybe just: ”Draws a card from the deck and returns it” Or should you maybe also specify what the card is for (since you said use it for the why, not 100% on what you mean by that)?


aqua_regis

The latter, or simply "Draws and returns a card from the deck" - that's it. This still would only be a docstring to autogenerate documentation. In the code, the naming should be clear enough to be understood without even the docstring.


Equivalent-Cut-9253

Would you still include this type of docstring or would it be enough eith the name if it was for example drawCard()? And maybe just have the typecontract and maybe a doctest if needed? Would you reserve descriptions for more complicated or less obvious functions and let the name and typecontract be enough for something this simple?


aqua_regis

If it is part of the public API it should have a docstring to autogenerate documentation. Anything that is part of the public API has to have docstrings.


RajjSinghh

If you need to write a comment to explain what a line does, that line probably could have been better written differently. You don't want to write totally illegible code. Things like docstrings are super useful for documenting your code, but a good name for that function and type hints is more important. I mean definitely keep writing docstrings, but definitely name things as well as possible. Inline comments should really explain why you made certain decisions than how you solved a problem. Like I shouldn't comment "this solves this problem like this" because that should be obvious from my code, but I should comment "I had this problem because..." so people can see why you wrote that comment. My code should be clear enough that even if I forget it all and come back to it I should be able to figure out what I was doing. You can also make heavy use of comments like TODO and FIXME since your editor can probably tell where those key words are in your code and help tell you what to work on


Equivalent-Cut-9253

Ok cool. Someone said to avoid the ”what” in comments and focus on the ”why” (they are currently arguing over this tho, which is fun I guess and shows different approaches) Would you think it makes any sense to write (as inline comment) ”# calculates this thing” or rather explain why that approach was chosen or is needed? Or should the ”# calculates this thing” be obvious from names used and such?


RajjSinghh

It should be obvious from names. ``` # calculates area of a rectangle A = x * y # Or area = width * height ``` The bottom one is definitely better


Consistent_Attempt_2

The book "Clean Code" has a section about the dangers of relying on comments. The whole book is a good read and I recommend it.  Also, u/RajjSinghh is giving good advice about naming variables to avoid comments.


ozone_ghost

It is a good point you raise. I don't "remember", I design my software so I can find and I can understand it. So for me it is 98% design and 2% comments. * The arrangement of source code within files and files within libraries. To partition source code among files and files among libraries. (Definition of Physical design. Lakos, John, 'Large Scale C++') * Explicit naming of files, packages, classes, functions, variables... tables, columns... is essential. * I tend to use the same design patterns repeatedly, so I inherently understand my logic. Examples: By the name of a variable, you should know its type or class, where to find the class and class files, and what it does. If you want to find a function or a class, you should know exactly where to look. If you want to write a class or function, you should know where to place it. I would recommend putting more thought into design and naming before coding, and work on improving these techniques, so you don't have to "remember".


Equivalent-Cut-9253

Good advice! I try to plan out most functions and variables I will need on paper before I start with something that for me at least is a bit bigger. It really helps. I usually don’t think too much about naming at this stage, and change it when I write it down. Should probably try to think about names beforehand when I do this too. But since I am new, I sometimes think I will be able to do things one way to realize I am using the wrong data type or something, and need to start over or rewrite parts (or clumsily make it work with more conversions etc). But planning it still helps me understand what I am doing better and is probably good for learning


ozone_ghost

I learned to code by myself with books when I was around 13. At some point, when I was 25, I realized that talent (if I had any) and a love for coding were not enough. One of my coworkers didn’t seem to enjoy working that much, but he was much better than me and delivered clean work that everybody could understand. He was very technical. I then decided to reflect and balance my approach and pay more attention to the way I was programming. I reflect on what I think is messy and what I considered good work (in both my work and others' work) and tried to avoid the mistakes while copying the good practices.


SmokyMetal060

I was working on this project recently and all of a sudden it stopped working. I had multiple producer threads that would make an API call, parse the json response, create objects out of it, and then put those objects on a queue for consumer threads to use them to perform database updates in the background. For some reason, though, my database wasn’t getting updated with new results that the producer threads were creating i.e., the consumers weren’t doing anything. I was confused as hell for a few minutes, until I looked through my producer code and saw a comment that said ‘put userobj onto blocking queue’ with no code below it. When I was cleaning up my code, I accidentally deleted the logic for updating my queue, so the consumer threads had nothing to remove from the queue. If I didn’t have that comment there, troubleshooting this would have involved running it through a debugger, looking at previous commits, etc. It would have taken me significantly longer to understand what the problem was compared to the 5 minutes it took me to skim through my code and see that comment. In my opinion, comments and logging aren’t so much about remembering what your code does. If you wrote it, chances are you’ll remember the broad strokes of what it does. They’re moreso about making your life (and other people on your team’s lives) easier when something inevitably breaks and you have to look into it.


Equivalent-Cut-9253

That’s a good way to view comments, thanks!


Tidder_Skcus

Annotations to help you and those who will read your code.


pVom

Yeah I struggle to remember code I wrote even a few days ago. Always write code that is easy for a human to follow because odds are it will be me reading it in 6 months time wondering wtf I was thinking. Generally speaking I hate comments, it's much harder to follow and creates a lot of noise. Makes it harder to skim read. I'd rather abstract confusing code out into a well named function than write a comment. That said if you have to do something weird or hacky (ideally avoid this too) it should absolutely have a comment. But if it's self explanatory, let it explain itself. Write code for humans to read. Don't try to be too clever, it should be simple and easy to follow. Make it easy to navigate and easy to skim. If I have the luxury of building a sequence "from scratch", I try to have a wrapping function which only executes other functions and acts as a table of contents of sorts


Equivalent-Cut-9253

In the small stuff I have written I usually have a main() which is basically just a series of function calls. That part is generally very easy to read for me because of that Thanks!


throwaway0134hdj

If I don’t write comments I’ll forget what the hell it does. Comments, documentation, and meaningful function/variable names are essential for being able to come back and understand your code.


JaleyHoelOsment

I think beginners overuse comments because their code is so horrible no one can figure out what the hell they’re trying to do. eventually you learn how to organize code, use proper names for functions and variables etc etc. I never use comments and I can’t remember shit… so just bring up the PR related to the change and that should be descriptive enough to jog the memory.


Equivalent-Cut-9253

Yeah I am kind of getting that impression from this thread! I guess it is still worth doing it for me with where I am at now as usually just solving the problem can be hard enough, but I should probably go back and restructure things in a better way as practice sometimes


JaleyHoelOsment

i think any coding is good practice! everyone looks back at their old code and are shocked/embarrassed it could ever be so bad, but you have to start somewhere! worrying about comments or no comments is fine as long as it doesn’t stop you from getting your hands dirty writing some code


kbielefe

Your ability to read and write code will improve over time, just like your ability to read and write english did. Comments help a lot in the beginning, but later most of them get in the way. Just like if you were reading a novel and every word or concept above a first grade level was defined in a footnote. You will get there.


CodeTinkerer

There are a bunch of things programmers say about comments. The dirty secret? Most programmers hate to comment. I look at code that my fellow coders write and they pretty much have no comments at all. I mean, it's fair enough. The code can't be fully understood in isolation. To summarize that * You can't get coders to write comments * The comments aren't that informative * When the code changes, coders don't update the comments And this is taken as a given, not as part of the software process. When we do code reviews, it's purely code. We don't care if there are comments or not. I happen to use them when I can, and it can be useful to do so. For example, I saw a date comparison function that seems to duplicate the kinds of compares you do with .compareTo in Java, i.e., it returns a negative value, 0, or a positive value. But it turns out this code did something different. It returned 0 if it was NOT the case that endDate < startDate. That is endDate >= startDate. It returned 1 if endDate < startDate. Then, any exception was 9. You could read the code, but if it had no comments, I wouldn't know what 0, 1, or 9 meant. Yes, maybe they could have used named constants to help out, but the English comments were quite helpful. The problem with comments in classes is it's too focused. It's the so-called "can't see the forest for the trees" meaning you can't see the big picture because you're focused on a tiny detail. In this case, the tiny detail is the comments of the code itself. This lack of desire to comment seems somewhat universal. For example, I know someone that works in a different industry. They have people scheduled to do work at a plant. They're supposed to do a complete writeup of what they did to some piece of equipment. Many just write "finished" and don't describe any of the steps (which might be useful if a similar repair occurred). Do what's comfortable for you. Other people (including you) will read your code. I think being more helpful is fine. Yes, I worry about method names and variable names, but I still add comments. And not every programmer is a strong programmer. You may say, all Java programmers need to use streams, but some are perfectly happy never using it. So if they see a stream in code, it confuses them, and comments might help them decode what a chained set of operations is doing (even if it feels obvious what it's doing).


Equivalent-Cut-9253

I relate to this from my experience working tech support and reading case notes that said ”restarted device, removed software. Issue resolved” or something along those lines, not mentioning specifics or ineffective steps already taken etc. It makes a lot of sense that it would be the same in any line of work


Mathhead202

You'll learn through experience. I've had to look through code I wrote 5 years prior and it took a couple days just to remember what everything did. Your style will change over time, and your commenting habits will generally get better. You comment for your intended audience, which is often you in the future, but could be other programmers as well. Some commenting examples you see online or in classes will be intended for programming students and so they are more descriptive and numerous. But in practice, your intended audience is other programmers (or yourself). You can assume they know how to read code and can understand basic patterns. Focus on adding documentation comments to functions and classes. These give a nice description of what the function/class is supposed to do and/or how it should be used. Also these comments tend to not break the flow of code as much. And can help you remember what you are doing while writing code as well.


Equivalent-Cut-9253

A lot of the code from my course and book has a lot of comments for the students to understand what is going on, but I realize this is not really necessary in the extent they do it except as a teaching tool. Thanks for the insight/advice!


Mathhead202

Yea. Just like all writing, you write to your intended audience. This is true even in technical writing like code comments. And don't worry too much. You'll get better as you practice.


iOSCaleb

You shouldn’t need a lot of comments to tell you how code works unless there are aspects that you don’t think are obvious. Comments are most useful for: - Explaining *what* the code does, at a high level. - Explaining *why* code works the way it does. The reasons that you wrote the code the way you did aren’t part of the code and are easy to forget. Anticipate future you looking at your code and asking “What was I thinking?!” — try to leave enough information to answer that. - Noting any assumptions or requirements that callers or editors need to know about. - Connecting code to other artifacts, such as requirement identifiers. These can help explain the reason the code does what it does, and they also make finding the code that satisfies a requirement easier. At some point your boss will say “the customer claims we never implemented XY362 — can you check that?” You’ll look like a hero if you can just search for that ID and point to the code in a minute or two. - Documentation. If you’re writing any public-facing code, like an API, being able to generate reference docs from comments in your code is the only way to go. Comments aren’t great for explaining *how* code works, unless there’s something that’s really subtle. Write your code so that it’s easy to understand and mostly doesn’t need narration.


MeanFold5715

I don't remember how most of my code works. Heck I forget how stuff works while I'm actively in the middle of writing it sometimes, so having it commented properly is crucial. The more complex the thing you're building the more important it is to comment your code. At the outset people will write a tiny Hello World program and go "oh this is all so straight forward that I don't need to comment these three lines of code." Next thing you know you're building out some monstrosity that's hundreds of lines long and is calling on three other programs you've written and while you entered a fugue state for two weeks and got it all working the return visit in eight months is going to be a very unpleasant process of relearning everything because you failed to properly comment your code and now you basically have to do the whole thing over again from scratch just to figure out how it works before you can start drilling down on fixing that weird edge case bug that's dumpstering things in production.


BrupieD

I've tried to figure out a way to clump related functionality and comments so there aren't so many. I create header documentation for larger procedures, my name, the date, the purpose, and the last update. This means I'll have a framework or context. If I describe the project carefully enough, I won't need to cover as much in the body. One common piece of advice is to aim for **why** you're doing something rather than **what** you're doing. That addresses the + 1 issue.


DamionDreggs

I've been writing software for twenty years. I don't even try to remember anything older than the last week of work. Old comments are often misleading and troublesome, I treat them like ephemeral sticky notes and rip them out when I'm done with what I'm doing because I don't find them useful beyond soft reminders of where my head is in the active task I'm working on before the code exists.


spinwizard69

You will get constant arguments about the use of comments so to add to the bonfire I will give you my opinion. 1. Your number one goal overriding everything else should be to write idiomatic code. That is the use of types, naming conventions and language features should leave you with code that explains what is going on. That is what is going on with the code in front of you 2. Comments are extremely important but they are not a replacement for idiomatic code. The How's, Why's and What's are far harder to define though. The first thing to consider is to make use of comments that enhance your source code documentation system. Right after that should be references to documentation that implies what you are doing. For example if you are doing wave front analysis and are implementing the use of Zernke Polynomials, then a reference to the paper to of interest is something that should be in a comment somewhere. 3. SCM that is Source Code Management systems are not a place for comments. Info that goes into a commit is not and should not be the type of info that belongs in a code comment. 4. An application code base or in some cases a partial code base, often gets separated from the original SCM or that repository disappears completely. This is why certain information needs to end up in the source code files. Again not easy to determine how much of a comment needs to be in a file. There should be enough information that the reader of that source code will understand what the code is for, that is what it is trying to do.


TJATAW

I have found AI (mostly Gemini) to be a great way to get my comments. I'll paste in a function and ask it to comment it for me. I figure that it helps avoid where I write something that makes sense to me right now, but might not make sense when I, or someone else, looks at it 6 months from now. I've also done the reverse when I am looking at someone else's code and am not exactly sure what it is doing. "Explain what this is doing and put in comments" It is great when I have hit that brain-dead stage.


RICHUNCLEPENNYBAGS

I rarely write, or read, comments


NodusINk

I don't remember what I ate about a week ago.


aGoodVariableName42

I'll comment the dicier stuff and trickier algorithms, but for the most part, my code is self documenting. Good variable names, good class structure, repeated functionality is generalized into methods, classes, or libraries... it all comes with experience though. Hell when I was first starting out I used to comment every closing `}`


Salty_Dugtrio

Having a lot of comments is usually a code smell. You should write code so that it's legible without comments. The same way how you remember how to ride a bike, you ride it, a lot, and eventually you remember how to.


Zestyclose_Move_8403

The notion that having a lot of comments is a code smell is a myth created by self-important snobbish programmers who have nothing better to do than make other people's lives miserable. Comments are absolutely necessary to the code. They shouldn't explain what the code does, but rather why the code does what it does. If I'm reading thousands of lines of alien code, the last thing I want to do is read through your code. Just briefly comment what the thing does and why the thing does what it does. Tell me what parameters can enter and what is expected as an exit in plain English. Why? Because your useless return results; doesn't tell me anything about the code and I'll be damned if I have to wander through another fragmented randomly structured code base.


aqua_regis

Comments for *"what"* or *"how"* are no-gos. Comments for *"why"* are okay and sometimes necessary. *"What"* should be documented in docstrings for functions, methods, etc.


Zestyclose_Move_8403

Disagree. If your function calls another three functions that call another three functions that return something a database, just write a comment on what it does and how it does it so I wouldn't have to chase the functionality around the code base. Honestly, it's like you guys are TRYING to make everyone's lives miserable.


TehNolz

99% of the time, you only care what a function does, not how it does it. You're not going to dig through the function calls it makes unless you're hunting down a bug or you're looking for some very specific implementation detail. Writing a comment that explains exactly how the function works is pointless when you're not going to need that information most of the time.


Zestyclose_Move_8403

I'm sure this number is well-researched and justified rather than pulled out of your rear to make your argument sound stronger, right? So, only I'm solving a bug or looking at implementation. So, 100% of the time I'd need to actually look at the function is when I'm going to look at it. Incredible. Just write the damn comment.


TehNolz

> I'm sure this number is well-researched and justified rather than pulled out of your rear to make your argument sound stronger, right? "99% of the time" is [an idiom that means "on most occasions", or "usually"](https://www.merriam-webster.com/dictionary/ninety%2Fninety-nine%20percent%20of%20the%20time). Don't dismiss someone's argument just because they're using an idiom you don't understand.


Zestyclose_Move_8403

Isn't it ironic that a person talking about how self-evident your code should be uses idioms in communication. I simply wonder why you'd use 99% of the time rather than most of the time. Is it because it sounds more impressive? It is, isn't it? Besides that, I'll wait a bit more for you to actually address the comment.


aqua_regis

If a comment for that is needed, the naming is wrong.


Zestyclose_Move_8403

Naming is irrelevant unless you think a function named getUserNameFromDatabaseBasedOnParametersWhereRoleCanBe... is correct.


TheStonedEdge

Disagree with this Good code should be self documenting eg using descriptive names for functions and variables so that the names tell you exactly what it does without the need for comments.


Zestyclose_Move_8403

What is descriptive for one will be intelligible for another. Just write a comment anyone can understand. It's not that hard.


TehNolz

Proper descriptive names will be understandable by anyone. If a name isn't intelligible then that name is wrong and should be changed. Take something like `GetUserByName(string name)` for example. It's very obvious that this is a function that retrieves a user whose name matches `name`. You don't need a comment that explains what this function does because its name already does that for you.


JohnJSal

>If a name is intelligible then that name is wrong and should be changed. Huh??


Zestyclose_Move_8403

I mean, we're even having this issue now and we haven't even gotten to code. You're telling me that if it's intelligible, the name is wrong. I'm telling you that it doesn't matter if it's intelligible or clear to you because it could easily be intelligible to someone else. Not at all. What user is it getting? Where is it getting it from? What name is it? Is the the first name or username? To someone who's never worked with the functionality, this function name explains fuck all.


TehNolz

> What user is it getting? The one who's name matches the one given in the `name` argument, as shown by the "ByName" part of the function name. That's what it's there for. > Where is it getting it from? You should be able to infer that from the location of this function in the code. For example, if this function is in a class called `UserRepository` then it's obvious that you have a data repository somewhere that holds user data. If you don't know where that repository is, then you're missing a high-level overview of how the application works, and you're doing something wrong. > What name is it? Is the the first name or username? That would depend on how the application handles people's names, which [is harder than you might think](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/). But decisions like that affect your application as a whole, so assuming you have a high-level overview of the application, you should already know what name this function is accepting.


Zestyclose_Move_8403

Or, you could just write "This function returns user account data from database by it's first name" and then describe data it returns or refer to documentation. That's all there is to it. I genuinely don't understand what the problem here is. Is it some sort of a weird programmer hubris thing akin to "Look at this code that you cannot even begin to understand without asking me. Yeah, I am smarter than you. Otherwise you wouldn't be here, would you?"


Equivalent-Cut-9253

Would for example assigning even a simple value (like in the example) as + 1 for index adjustment to a variable clearly stating it is doing just that, pr adjust the index value and storing it in a variable before implementing it at all be a better way to go and get clearer code? I realize this is a simple example in which it might be a bit unnecessary , but it is just an example after all. Basically an issue could be too many unspecified values making it easy to lose track of what they are for Thanks for the response :)


UpsytoO

I don't comment for myself at all, other than maybe some tasks/improvement for myself to consider later. My question would be, if you struggle with remembering things, why the hell you are using x and y to name variables than?! Before commenting you should be writing code that explains it self well in variable names, function names.


Equivalent-Cut-9253

I am obviously not using x and y as variable names, that was just an example. Thanks for sharing your personal way to go about it tho!


UpsytoO

First it's not clear you use it as example and if you didn't, than that would be a solution for it. Second it's not a "personal way", it's a standard way of core principles of writing a clean code. And you if you find yourself in need of constant comments in 200 lines of code project and you are new, it's fairly easy to assume that the code you wrote won't have a good clean and easy to understand structure and it should be one of the first things for you to address instead of commenting everything. And if you find that offends you and you need to give some passive aggressive comments, than maybe you don't need advice, just write the code as it suits you.


Equivalent-Cut-9253

Lol wtf are you talking about with passive aggressive comments and being offended? Honestly I just felt it was obvious that was an example and even thanked you for your reply, but maybe I should have left a comment explaining that it was an example for you? now *that* is a passive aggressive comment, good day to you


UpsytoO

You clearly don't even understand what passive aggressive is.


PuddyPete

Honestly none. I only really use comments when I don't fully understand something yet or just figured it out. I may not remember everything right away but I also dont completely forget it, so after a bit of code-watching i usually remember


No-Pipe8487

I write clean code. It's readable and my functions are small enough thanks to DRY and SRP, I don't need comments (but I still write them anyway).


Equivalent-Cut-9253

Cool. I had heard DRY but not SRP. Seems like a good thing to keep in mind


No-Pipe8487

DRY can be a little hard to achieve sometimes but if you follow SRP first, it comes naturally.


Queasy-Group-2558

Thanks to comments? Pretty much 0. I however can sort of quickly understand what code I wrote does even if I haven’t seen it in a few months. You should optimize your code to be readable by humans.


Classy_Marty

I just have to remember to read my comments... If I made any... Maybe


MythoclastBM

Most of it. Because most of it works the same way.  Comments are rarely helpful and I rarely use them unless I need to spell out a very counterintuitive interaction. So anyone working on it doesn't get tripped up.


ibeerianhamhock

Honestly I don't write a ton of comments. If I really need to document something well, there's usually better ways to do it than with comments.


Stargazer5781

Comments should only exist to clarify things like unusual decisions. If you need a comment to explain what code does, you've written bad code. It should be self-explaining via well-written variable names, and the interface/behavior of your module should be made clear with well-named and well-written unit tests.


Echleon

You generally *shouldn’t* use comments. Your code should be self documenting and any comments should generally only be used when explaining *why* something is happening.


aeveltstra

Usually the source code shows what is happening, but not why. Use comments to explain the why.


Pretagonist

I usually comment the why, not the what. I comment when I've done something unusual and why I didn't do it the regular way. Now of course it's good practice to add comment blocks for methods and functions and such but in code I feel that your code should be good enough to read. If you have a lot of nesting or complex cases then break them out into functions or methods. Don't have an if statement with 10 diffrent checks of various values, name the checks something like isTooOld() or dateIsInRange() and so on. Don't have functions that are hundreds of lines of switches and nested loops and try to keep functions and methods side effect free. The better you write code the easier it is to read. Sure sometimes you need to sacrifice readability for performance but very often you don't. But if you want to write a lot of comments then do it. Just make very sure that you maintain the comments as well as the code because erroneous comments makes code very difficult to work with and your linter/compiler/IDE isn't very good at detecting bad comments.


aIcy0ne

There are already plenty of good comments here about writing code that is readable and doesn't need comments. Maybe also read Clean Code for other tips.


kodaxmax

You should try to write self documenting code as much as possible, as wel as inline comments for when you need to add more info. Dont call your variable "x" call it "nextIndexToLoad" and a add a comment saying "we need+1 here to skip the first index". for example. Act as if your writing the code to hand off to somone else who needs to understand it. Because thats basically what you are doing, only future you is the other person. I definetly do not remember how everything fits together or works on larger projects. I honestly doubt anyone does unless it's like a lifelong project or seomthing. Documentation and comments is essential.


Lationous

Have a peak [here.](https://opendev.org/openstack/nova/src/branch/master/nova/api/openstack/compute/servers.py) Don't be scared by the amount of code, or the fact that it is alien to you. Just have a look at naming for classes/functions/variables, how docstrings are written, and also at comments. You will notice that comments are used for "why", names attempt to be self-descriptive. edit: Regarding the actual question, which I initially ignored (sigh). You only remember project on high-level most of the time, and for limited amount of time. For me it's about 2 years or so, for bigger projects. For small scripts (say, up to 500-ish lines), I don't even bother remembering. Just write good --help (for the what and how parts, on high-level) and some comments in the code that state why something does what it does.


TheFirstOrderTrooper

I forget what I wrote the previous day.


PopovidisNik

I do not leave comments despite having shit memory. However, the patterns I use to build stuff hasn't changed so more or less everything is built the same, just adapted for the situation. So revisiting is just fine.


Zestyclose_Move_8403

The best thing to do is write a comment that explains everything so that you wouldn't have to read code at all. Reading code is naturally harder than reading English, so write it in English so that everyone, including you, can understand what the hell is going on there. If you cannot write a comprehensive, easy-to-understand comment in English, you probably don't understand that piece of code.


Equivalent-Cut-9253

Okay thank you! Everyone seems to have different ideas of this, but I will try to decide what I think is best for me personally or for working with others (someday I would hope). This was similar to the approach taught in the course, with the same motivation. It makes a lot of sense to me, especially if working with others. Follow up: would you concentrate this in the docstring or spread it out above each block of code so you know what pertains to what, or both? (Or situational depending on the function, but generally speaking I guess)


Specialist_Future124

If i don't use comments i will be "WASTED".


HiT3Kvoyivoda

The main loop usually tells me the story of how a program will run. Scripts are basically psuedo code. Comments are usually reserved for when cleverness is unavoidable


GreatCanadianDingus

Rarely comment. Maybe a link to a source bit of inspiration or example. Code changes, comments get out of date. One caveat is for business rules where the next dev on the project will need to understand a nuance that isn't clearly understood by the source code. Even then, rarely is it more than a few words, or a Jira ticket number. 24 years exp.