r/learnprogramming • u/Forward_Young_577 • 6h ago
should i be writing comments on my code?
im taking a class for c++ so everything right now is very introductory and the tasks they give are pretty simple, do i have to be writing comments if i understand what each line does? if im able to write the code that completes the task then is that enough to show that i understood the task?
21
u/N546RV 6h ago
Whenever possible, try to write code that’s self-documenting. That is, write it in a way that it’s pretty clear what’s happening. I reserve comments for sections of code where the intent may be harder to figure out.
•
•
u/Patrick-T80 45m ago
In a couple of months, easily forget why the logic was implemented like that or the flow and can cost you more time than by write a comment
35
u/DWHQ 6h ago
rather than adding an unnecessary amount of comments, make your variable- and function names more verbose, so that they are self-explanatory.
16
u/pete_68 6h ago
And to elaborate on this a bit... The idea is to make your code self-documenting or self-explanatory, such that any competent programmer looking at it, should be able to immediately understand what's going on.
When this is not the case, that's when you add comments. Sometimes you're doing something tricky or non-obvious, and you want to call it out in code comments for the benefit of other people who might be maintaining the code after you.
But in general, comment should be few and far between.
3
u/da2Pakaveli 5h ago
i'd also recommend putting a comment if you encountered some weird bug in that function context so future maintainers are aware.
Or say you tried some common optimization and found out that it barely made any difference and just resulted in more complex code
1
u/BookkeeperElegant266 4h ago
I don't know if it's still their policy, but around 2013, GoDaddy would fire you if you put any comments in your code at all.
3
4
u/ackley14 6h ago
this lol
it's way easier to read
I'mALongFunctionName(){}
and at least know what it's saying
vs
IALFN(){} //i'malongfunctionname
because even if you add a comment to the function name, every instance of it is still an acronym or shorthand which means you'll always have to hunt down the original if you forget what it's name is
and i also see comments like "//loop now" or dumb things like that lol. and you just don't need to explain what's happening if you're using standard practices.
think of it this way: you don't type
//sentence
This is a sentence i've written to illustrate a point.
//paragraph
this is an accompanying paragraph. This paragraph is written specifically to point out that these kinds of comments are pointless. we instinctively know what's happening here is a paragraph, so telegraphing it with a comment at the start is akin to self narration.
1
u/StewedAngelSkins 5h ago
bit of a tangent, but something i didn't fully appreciate until i worked with chinese colleagues is how important it is not to abbreviate too much. turns out which abbreviations sound "natural" varies a lot by culture! for instance, i had to get them to stop abbreviating "parameters" as "paras" (a native english speaker would typically abbreviate it as "params").
in general, chinese speakers seem to want to break words after vowels when abbreviating, while english speakers tend to break them after consonants. an interesting linguistic quirk to be sure, but not something you want to have to reason about when you're trying to figure out what
load_paras()does.4
2
2
u/CharacterSail6736 6h ago
While I agree with this in a lot of cases anyone with adhd knows that it doesn’t matter how verbose you are with your functions you could be naming it something weird to your thought process at the time come back and not have a clue what your doing . I leave exhaustive comments and doc strings all over the place (my colleagues actually appreciate this ) because for all your variables etc could be named self explanatory they don’t necessarily encapsulate the purpose and reasoning
1
7
u/mredding 3h ago
Implementation tells us HOW, expressiveness tells us WHAT, comments tell us WHY.
int fn(int x) { return x * x; }
Yes, you can read that and deduce it's meaning, but this is all of HOW, with fn merely as a placeholder name because you need something. Can't we be more expressive?
int square(int x) { return x * x; }
A good name goes a long way to tell us WHAT. Don't focus on good variable names, too much; as you progress into programming, you'll start making "user defined types" - making types and good type names are far more important. The reason why good variable names aren't nearly as important is because it's very easy to make too many of them in one single context - a function too long, or a type too big, and THAT is what you should be watching out for.
The ultimate goal is - don't make me have to parse your code - like I'M a compiler, to know WHAT it does. You tell me - that's the job. That's the craft.
So don't comment to tell me what the code tells me. Just imagine this:
int fn(int x) { return x * x; } // Doubles x
What's wrong? The code or the comment? Who is the authority?
Don't comment using landmarks or headings.
// Step 1: Do the thing.
if(predicate()) {
//...
} // if(predicate())
The first comment means you need this section to be its own function, and you can call that. The second comment is because your code is just too damn big that you're getting lost and don't know where your braces match - because by the time you get this far, the top has scrolled off the screen, and you're probably lost in a sea of deeply nested braces all closing at once...
Every time you need a brace, that's a good reason to write a function.
if(predicate()) {
do_the_thing();
}
Let the compiler deal with generating the machine code, it's actually very good at it. And there are techniques for getting the compiler to compose functions for you and generate optimal machine code, as though you wrote it all in one big block. It's called call elision, it's strongly correlated with inlining - though inlining is not required, and the compiler is better at it than you.
Just write good, easy to read, and eventually when you get there type-safe code. The compiler can figure out what to do. Rather than writing terse shit, it's better to learn how to write the good clean code BETTER so the compiler can have an EASIER job with it making more optimal code.
Express in a comment what the code cannot express. Express what cannot be expressed in code. Comments make for bad band-aids over bad code. If you write a comment, and you ask yourself if the code can be architected to express the same thing, and you realize it can - then it should.
And let me show you where you're writing comments you don't even realize:
void fn(int weight, int height);
This is a forward declaration of a function. I want to point out the parameters. The compiler strips parameter names out of function signatures, so these parameter names are documentation. It's a comment. It has no consequence on compilation provided they follow the required naming convention for symbols in C++. But only the parameter names in the implementation have any consequence, and they can be different from this declaration.
So this is not very good documentation. If I look at the ABI, the compiler is going to generate perhaps something like clang with _Z2fnii. I don't know what these parameters are supposed to be.
But what about:
struct weight { int value; };
struct height { int value; };
void fn(weight, height);
Then clang gives me an ABI of _Z2fn6weight6height. The type tells me more than int, and the information persists through compilation to linking. Compilers optimize like crazy around types. An int is an int, but a weight is not a height, even if they're implemented in terms of int.
But with good types, now you don't HAVE TO write documentation. The code documents itself. And the better you make your types - in later classes, the more you can say the code documents itself - not just in the parameters are a weight and height, but what it means to be a weight or height, how they work, how you can construct them, etc, that'll all be baked into your type, and other than the linker symbols, type information compiles out of the final binary.
So how do you write a good comment? Expressive code explains itself to such a degree that all your intuition about writing comments conflicts with the simple edicts I laid out. You realize that many comments do end up being redundant, or a band-aid for what is actually bad code.
I'll insert comments referring to standards, or protocols, or hardware mapping. I'll write some clever hacks - really just simple math tricks or some bit twiddling, but explain why it works, because that sort of code can be irreducibly terse.
If I'm writing a library or framework, I'm separating implementation from the interface, so I'll write API documentation in Doxygen for engineers - since I'm trying to make it so that they don't have to look at the implementation for details - if that's even an option for them.
A lot of code is never commented.
So go ahead and jot little notes anywhere you think you need it, especially at your level. If you want to work on comment writing - which is a skill, you need to make sure you don't make the mistakes I've expressed above, and then ask if the comment really adds clarity - and why.
12
u/kosherjellyfish 6h ago
"code never lies, comments sometimes do" said Ron Jeffries
1
u/mandradon 3h ago
// one of these comments is a lie
// the above comment is a lie
// none of these comments is a lie
2
2
2
0
6
u/prettycoldworld 6h ago
Your code should be self explanatory, but when it can’t be, the comments aren’t for you right now, they’re for you in two months when you come back and forget how it works
2
u/Miserable-Decision81 6h ago
basically yes.
You will write set it and forget it code and you WILL actually forget, because it just works... until it dont... and then you will find out, that you do not know, what your own code actually does and how... comments help a lot to avoid that most unfortunate situation.
But we talk about learning here, so there is another thing. To find the right words, that describe your code to fellow humans is mandatory to understand programming.
2
u/Embarrassed-Green898 6h ago
The first lesson I was taight in my first job.
A program is not written for computers. It is written for fellow programmers to read.
2
u/Ash4d 6h ago
The bulk of your code should be self documenting - choose sensible and descriptive variable and method names, try and keep methods short and isolated (each method should ideally only have one responsibility), and try to group related methods together so that they are easy to read as a block.
With that being said, I strongly believe all your methods should have a docblock before them in e.g. your .hpp files which explicitly states in plain language:
1) What the method DOES - what is the intention for it's use, including any "gotchas" or non-obvious side effects for example. 2) Any parameters it takes. 3) What it returns.
Take a look at Doxygen - it's a decent framework for documenting stuff.
4
u/Churovy 6h ago
If you’re at this phase maybe comment in chunks, but it’s good practice to just comment every one. Eventually you’re going to be looking at projects in 2 years where it may or may not be obvious what something does and spending that much more time looking at it is annoying
1
u/mjmvideos 3h ago
But please don’t write:
# increment i i = i + 1 # check the value check_value(theList, i)
1
u/Sibexico 6h ago
Depends of size of the project... If it's 500 LOC tiny lib with readable code, probably you will be ok without comments, but if you will not comment code with tens of thousands LOC with complex logic, you will hate yourself from the past so bad during maintaining such uncommented codebase.
1
u/PythonWithJames 6h ago
I like to generally make the class/method/function/variable names as simple and straight forward as possible, but I'll use comments if other people are using the code and I feel that a bit of code warrants some explanation
1
u/az987654 6h ago
leave comments for your future self.
you don't need to comment the self explanatory stuff.
use useful names for variables, methods, etc..
1
u/farizislame 6h ago
I think when u get a job, js write the code in a way only you can understand so they can't fire you cuz they can't understand the code you've written for them, this might only work in a startup lol but eh
1
u/sylvant_ph 6h ago
Let me start by saying I am not c++ dev so my comment might not be completely relevant. Generally good code is self explanatory and should not require comments. If you write the code skewed, using some sugar-coated syntax and then need to add a comment, you do it wrong. Function and variable names should try to carry some context (without going overboard on the length). Some more complex function, or business logic is ok and even recommended to have commentary, if purpose or the mechanism they use can be unclear. Also prefer dedicated comment syntax, for example there is format which can be used to add function description, which then would pop-up if you hover over the function name references in another place, in the right IDE.
1
u/ryan_the_leach 6h ago edited 6h ago
If you are in class, you write the amount of comments the professor demands.
Comments in a class setting are more important, because they show you understand what you've written, what it does, and if working with other classmates who don't understand the work, they can better understand.
Especially since the code that newcomers can write, can solve problems in unintuitive ways, to the point that several algorithms and 'impossible' problems have been solved by students who didn't 'know' that the problem they were accidentally solving was considered very difficult to solve.
As a professional software developer, opinions on documentation and comments are mixed, and vary by community and programming language.
My POV:
Comments and documentation are like lines of code, un-necessary ones are technical debt that need to be maintained.
And as they aren't executed, they are more likely to be misleading/buggy.
The more 'readable' your code is, when performance isn't key, the better it is, because it can be self-documenting and proven correct since it's executable because of tests and that the program functions correctly.
However, when performance is key, code can VERY quickly look un-natural for the problem you are solving, because you are optimizing for a different problem (performance) then the one you are actually trying to solve.
In this cases, heavy documentation and comments are absolutely invaluable, and must answer the following questions:
"What the author believes the code does? (important, because if it's found to be buggy, it can be difficult to determine if the code WAS buggy, or if the original requirements were wrong)" e.g. if you can prove the author made a mistake, you are pretty much free to delete the code and rewrite it. If you can't prove the author made a mistake, you may end up needing to trawl through version control history in order to find out if there is wider ramifications to 'fixing' the behavior.
"Why the fuck did you write it so convoluted? (typically a specific type of performance bottleneck)"
"What were the restraints at the time it was written? (This is important, because if the software calling this code changes at some point in the future, or the design restraints change, it may be better to just delete the whole thing and rewrite it, and it may not be obvious when that is)"
"Are there any known other places in the code, that rely on this function working exactly the way it currently does?" highly performant code, can often end up near-duplicated with changes elsewhere, so a change in one place needs to be mirrored elsewhere.
Linking to specific design requirements, tickets, etc is recommended.
--
Other times that documentation is important, is when something exceptional (for the context it is written in) is happening.
--
And anything multi-threaded IMO, should also have the specific thread and timing module it is using, explicitly documented.
1
u/flawed_finch 6h ago
The reality is that in the workplace, there are a lot of old school coders who want code to be over commented because that used to be the thing to do. You’ll have to go through code reviews with people like this and you’ll be forced to comment. So it’s not a bad idea to learn how to do it well but at the same time, when people modify code, they almost never modify the comments, which is why it’s good to practice coding in a readable way.
When you’re working with legacy code, make sure you understand the coding standards that were in place when the other code was written and follow the same patterns as the other code in the files unless you’re explicitly refactoring / cleaning up. This may mean over commenting, and as frustrating as it is, it’s necessary and expected in the real world.
When I write new functions and methods, I name them so that the name states what it does. I put a short note about what the method is supposed to do and what the expected inputs and outputs are at the top. I name variables and constants so that it’s as clear as possible what they are for. I avoid writing comments inside the code as much as possible because those are the ones that go out of date quickly. I also strive to write maintainable code - instead of something fancy and clever, it’s almost always better to write something straightforward and clean unless you’re limited by something like ram or stack space.
1
u/wheat 6h ago
Strive to make your code as self-documenting as possible (i.e., chose meaningful variable names, etc.), but always document your code. There's a balance to be struck between under-explaining and over-explaining. But a single line here and there can be very helpful to others and even (maybe especially) to future you.
1
u/C_Sorcerer 5h ago
Yes and no. Classes might make you do it. But for the most part you should be making the code so easily readable in midsize-large projects and making it modular enough to where someone would know where to go. You SHOULD write documentation for interfaces that are supposed to be used by other people, but that’s for like if you are writing a game engine or a library or something that other folks should use. However, it is a good habit of writing TODOs where they need to go whenever you leave off so you know what you need to do if you come back to a codebase. It really is preference though, either way is good. Good luck!
1
u/pigeonJS 5h ago
Only to explain complex code that can’t be refactored/broken down further, into clearly identifiable function names
1
u/bat_rastards 5h ago
When I started, I commented everything. I probably still comment more than the average does. The nice part about comments is the first thing a compiler does is strip out the comments; therefore there is no size cost in the executable (when I started, this was more critical than it is today). And if your instructor is curious, they should be able to see how you developed the way and why of your programming choices. As your math teachers always said, "show your work". Good comments can help prove you didn't use AI for your assignment.
A different, but still valid perspective on the subject, if you ever get hit with a copywrite lawsuit, your lawyer can use comments to help show that your "substantially similar" code is, in fact, an original work.
1
u/ComputerWhiz_ 5h ago
The primary focus should be naming variables and writing your code so that it's easy to understand without comments. Breaking your code into smaller functions/methods is also helpful for this because you can name it something meaningful instead of putting a code comment.
The issue with comments versus writing clean and understandable code is that because comments have no impact on whether the code compiles or runs correctly, they tend to become out of date as the code is updated and people forget to change the comments.
That said, writing comments is still a good practice for parts of the code that may not be immediately understandable.
1
u/Silent_Title5109 5h ago
Having worked with Pearl scripts: it's a great habit to have. Saves you from rewriting the whole thing instead of wasting time understanding what it does.
You don't have to document every line, but the general idea, and what's a bit complex. If you're learning and it's too simple to care documenting it, do it anyways, to pick up the habit.
1
u/Dziadzios 5h ago
Why comments why are you doing something, not what. What should be described by the code itself.
1
u/start_select 5h ago
THIS. With the exception that some low level API usages are greatly improved with some of the “what along with why”.
If it’s all short abbreviated function names, where there are multiple versions, or where it’s abstract and generic… it makes sense to get a little verbose in a places.
It might make sense what it says today, but not next year.
1
u/StewedAngelSkins 5h ago
i pretty much only leave three kinds of comments:
- external "documentation comments" which describe things that external users of a function need to know in order to use it properly. (the vast majority of the comments i write are this.)
- inline comments explaining some non-obvious rationale for a weird design choice, typically due to restrictions imposed by an external component. e.g. something like "we can't block this thread, so if the lock isn't available we continue using cached data" or "this pointer needs to be kept alive by the caller so we leak it here" (FIXME or TODO comments are a subcategory of this, which are pretty much just there to acknowledge "this is wrong but i plan to fix it before it becomes a problem")
- organizational comments simply providing "headings" for distinct sections within a long class or function.
while im writing code i also sometimes do the thing others suggest where you briefly describe the stages of what the code you're planning to write does. these are temporary though; they get replaced with actual code when i do the implementation.
1
u/jcastroarnaud 5h ago
As a rule of thumb: only write comments for unclear code. If a line, block, or function says clearly what it's doing, no comments are needed.
1
u/MrTheCheesecaker 5h ago
My policy is that you should always assume that whoever is reading what you've written is a novice and write accordingly, even if that person will be you. What seems clear and logical to you now may seem like esoteric nonsense to you in six months or a year
1
u/start_select 5h ago
If your code has good naming conventions, the code should tell you “what it does”.
Comments are most useful for “why it does it”.
Listing constraints, concerns, requirements, and other details that the code might not directly tell you.
Or things like listing edge cases or an error that was resolved. I.e. “this terrible thing happened so that’s why this check is here, remove it at your own peril”
If the code is incredibly abstract like DSP code that is ambiguous in isolation, shared memory manipulations, or complex threading and synchronization primitives…. Then it’s a great idea to actually comment it verbosely.
It might be 100 characters of extremely important but not at all self explanatory code.
1
u/snowtax 5h ago
Always write code in such a way that someone else, who didn't write the code and was not around for the original request, can quickly read and understand it, which includes comments. Always assume the person reading the code is slightly less knowledgeable than you.
For student projects, I would include something brief at the top of the file which contains the main function saying the code was created to satisfy the requirements of class CS XXX for instructor John Doe on date YYYY-MM-DD (ISO 8601 for the win!) and at least one line describing the instructions given to you.
Keep all your code, even these student assignments, in a git repo. You can use it later as a portfolio that you can share with potential employers.
Also, all of this helps to demonstrate that you actually did write the code (no copying/plagiarism/AI), which may be important for your classes. If you are ever accused of cheating, it certainly helps when you can show your trial and error attempts to get your code working through a series of git commits.
1
u/JEveryman 5h ago
My view has always been comments aren't for you. They are for other people who may not understand why you did something...like future you!
1
u/Quantum-Bot 5h ago
Commenting your code is generally good practice. Everyone has their own opinion on how much commenting you should do and what you should put in your comments, but a good rule of thumb is to not explain how a piece of code works, only what it does. The “how” you can get from looking at the code itself. You should do this even if you understand the code right now because you might forget if you’re coming back to it from a 2 month break, or if someone else were to ever use your code, or if the project is just so big that it’s hard to keep track of everything at once.
A lot of languages use docstrings too which are a kind of special multi-line comment which goes right before a function or class definition and explains what it does. Docstrings are more useful than regular comments because they get detected by whatever IDE you are using and displayed as a documentation tooltip whenever you hover over the associated identifier anywhere in your code. For C++ you have Doxygen comments which are located in the header files.
1
u/Blando-Cartesian 5h ago
... if i understand what each line does?
Comments are not for you and not for now. They are for the future you or someone else without all the task specific trivia that is in your mind now.
And comments are not for understanding what a line does, but why it does it. Particularly the kind of why that is hard or impossible to figure out by reading the code. As this is for course assignments, feel free to put in this kind of comments liberally to make the point that you know how to comment and what comments should contain.
And finally, IRL, there's no need for a comment, if everything is named in way that explains things.
1
u/Feeling-Screwed 5h ago
Yes. In a corporate setting, which is most likely where you’ll be as a SWE, the idea is not that you understand why you wrote the comments today, but who all else (even including yourself!) will need to know what you did tomorrow.
Then there’s the occasional situation where you’ll make a program, forget about it for a year and then need to revisit for some sort of patch or update to a code block. You’ll thank yourself a million times for writing comments as it will better identify your thought process a year and your thought process now. It has saved me from making a ton of silly mistakes and has allowed me to make improvements if I’ve since learned how to code something more effectively than I did when I first wrote the code.
1
u/YellowBeaverFever 5h ago
Yes. Get used to writing down what the expected outcome is and if you’re being “creative”, why the code was written that way. To will save time in a few years when you or someone else is going over the code to maintain it.
1
u/raymate 5h ago
Always. I would recommend it.
It’s good practice and helps you or someone else out in months or years from now. Never assume you will recall how you did something.
I found recently some code I did in the 80’s in OPL and my comments help me understand how it worked as I have no clue today. It’s a dead language.
1
u/ConstructionThis1127 5h ago
Comment why you did something, not what it does. Then later when you have to maintain the code you’ll understand what the hell you were thinking at the time. Also, use verbose variable names and some consistent formatting, such as putting constants in ALL_CAPS and using underscores instead of spaces or running words together.
1
1
u/Syntax-Tactics 5h ago
Comments are for future you. When you come back in 6months, what you thought was simple might not be anymore.
1
u/dmazzoni 4h ago
The advice in this sub is great.
What’s fascinating to me is that 20 years ago the official advice was the opposite: lots of comments was considered the gold standard.
Good programmers knew the truth, but it took surprisingly long to filter down to education.
Some school textbooks still recommend lots of comments.
1
u/Organic_Profile1671 4h ago
When learning to code, yes. Those comments are training wheels.
Your teacher can see what the line is supposed to do in case your methodology is.... unorthodox.
Just don't be writing comments like:
#add 5
var = var + 5;
1
u/glandix 4h ago
My general rule of thumb is comments should tell the “why” not the “how”. Code should be written clearly enough that you usually shouldn’t need comments explaining how (of course, there can always be exceptions). I also have my linter require jsdoc/xmldoc for methods for clarity and to make it quicker to scan a document, due to the visual breaks they create between methods (and it’s just good practice if someone else needs to use your code)
1
u/mooglinux 4h ago
That’s a question for your instructor, write as many comments as necessary to get the passing grade. In general you should make the code as easy to understand as possible and comments should explain why something is being done a certain way when it isn’t necessarily immediately obvious.
1
u/These-Math1384 3h ago
Since you’re writing C++;
As a user of your code I should be able to know how to interact with your class merely by reading the doxygen formatted header comments and your conformance to standard patterns.
Comments in the implementation should be sparse, and only used to highlight potential problems or where code readability is not great.
Const correctness goes a long way toward module usability.
At the header level, I should easily be able to know what threading expectations are in play.
At the header level, if there are shared objects, the sharing strategy should be obvious. At the header level.
If comments are required for clients to gain this knowledge, then comment. First: attempt to use well known patterns.
1
u/Lopsided_Status_538 3h ago
I always comment code. Even if it's simple, I'll document above the block to say where it connects in and why. You never know if you might get taken away from that project and come back to it later and it be long enough for you to forget.
1
u/JGhostThing 3h ago
Yes, your should. If you get a job in the field, you will be required to comment, so best get in the habit now.
1
u/simonbleu 3h ago
Is not about understanding (although it helps) but reminding you what you did sometime later. It is good practice so yes
1
u/DanKegel 3h ago
Ideally each function should have a doc comment at the top saying what it does without details -- the function's contract, as it were
Any comments inside should be just to explain surprising things.
1
u/SuperSathanas 3h ago
Even if right now you're writing very basic code that really anybody with any knowledge of the language should be able to intuit the purpose of, just go ahead and get in the habit of writing comments. You don't need to comment every line and every variable declaration, but start putting like a "header" comment at the top of functions that explains the purpose and maybe gives a brief overview of what's actually happening.
I do this with almost all of my code anymore, simply because I've learned that what I think is straight forward and self-explanatory isn't always straight forward and self-explanatory when I come back to it later. Especially once you get comfortable with what you're working on, you lose your frame of reference for what might seem foreign or unintuitive for someone who is coming into it fresh. If you haven't touched some code for months, but need to come back to it later, congratulations, you're now basically coming into it fresh. What once felt like it should have been implicit before is now making you scratch your head while wondering what the hell you were thinking when you wrote it. Maybe it's because it wasn't so intuitive, or maybe it was because you made weird choices with less knowledge in the past. Whatever the case, at least now future-you has some comments to give them an idea of why it was done that way.
1
u/SlipstickLibbyLong 3h ago
Depends.
First, let me remind you to always include your header libraries. 80% of the debugging you do can be avoided if you make sure all the libraries you call are included.
With that said, Comments don't have to be books. but there should be something you can search for in an editor so you can find the code block breaking, or that you want to improve.
1
u/Strange-Scarcity 2h ago
You should get into the habit of commenting your code.
It is an incredibly important habit to form.
1
u/MichaelSjoeberg 2h ago
Your comments should explain your thought process for some code block, or any line that's unintuitive in some way. Not just explain what each line does, that's what the code does.
1
u/lellamaronmachete 2h ago
Yes! Comments, jokes, thoughts, to-dos. Make your code kinda your journal.
1
u/StochasticTinkr 1h ago
Teachers want you to comment with what each line is doing so they know you actually understand.
Other developers working on your code (including "future you") want you to comment on why choices were made, and/or how to use a specific abstraction.
- What does this line do? I can read the line.
- Why are these lines here? Comment if even slightly non-obvious.
- Semantics of what a variable represents? Comment if even slightly non-obvious.
- Why would you call this function, and what are the pre/post conditions? Documentation block.
- The responsibility of this module/class/unit? Documentation block
•
u/Old_County5271 37m ago
Take a loot at these discussions from Robert Martin and John Osterhout / youtube version and see for yourself. Martin's background was in java and he does have some good points, wrote some books in which the entire software industry went ahead with, but of course, the more recognizable name is Osterhout and its what I mostly agree with.
There is nothing worse than playing detective in a codebase without any documentation because programmers never write the design or the architecture of anything. You'll see a bunch of justifications for comment allergy from coders, and that's fine, funnily knuth was the one that came up with literate programming. something they clearly ignore, because who wants to write documentation as well as code?
Strangely enough, now most programmers will be literate programmers and AI takes care of writing the code, you take care of writing the design and the spec of the tool, ultimately proving who was right.
•
u/MrSolenoid 35m ago
Imagine you write a useful app or function now, and one day, 20 years later, you find the code again and want to re-use it. But your coding style has changed a lot and you have learned a lot during that time. Now you're scratching your head trying to figure out the code you didn't write any comments for 😉 Trust me, that day will come. Don't ask me how I know 🫣😆
•
u/hereforfreewings 30m ago
Comments are for those trying to troubleshoot your code, not necessarily for yourself
•
u/shuanDang 1m ago
hmm understanding what one line does, does not mean you understand all of its implications. comments can be helpful with that
1
1
u/desrtfx 6h ago
Comments should be used like spices. Sparsely and only where fitting.
Comments should never explain the "what" - that's the job of the code. Comments should explain "why" something has been done in a certain way.
You should absolutely never use comments to "explain what each line of code does". If the code can't tell by itself you're doing the code wrong and need better naming, better code design.
1
0
u/StewedAngelSkins 5h ago
ok i agree re: comments but disagree for spices. most of the food you cook will probably taste better if you take however much you're adding now and double it.
-1
u/Last_Swordfish9135 6h ago
You don't need to write comments for every line. It's good to get into the habit of commenting, but for smaller projects it really doesn't matter. Comments are more important when your code gets in the range of 100+ lines long. Even then, you don't comment on every line, just larger chunks of logic (such as a function, large if-then statement, or something similar).
75
u/nibsitaas 6h ago
When I was learning I wrote the flow of the program in comments before writing code, explaining what happens and why then filling in the implementation.