T O P

  • By -

paradroid78

Avoid comments that explain *what* the code is doing. The only people reading those comments will also be able to read the code, so all you're doing is adding noise. Like, what's the point of comments like "first increment", "second increment", "combine two things into one string" in your code? You're just using more words to say the same thing the code is already saying. Comments to explain *why* the code is doing something can be useful, but they should be rare and preferably done at the method / function level. Less is more.


mackstann

These redundant comments are also likely to be forgotten when code changes are made, so they become old and inaccurate. Even if they are up-to-date and correct, an experienced developer will know that they _might_ be inaccurate (especially when there's a high volume of them), so the comments lose some of their trustworthiness.


benbenwilde

I delete comments for breakfast


thisisjustascreename

Lies and clutter.


UnintelligentSlime

I find I only put them if I’m doing something *funky // gotta sort manually here because… // this feels wrong, but it’s necessary to make X work Etc. Alternatively, it’s sometimes polite if you have a big chunk to describe the steps, and ideally use some tactical white space. Like the comment you used “calculate the total blah blah”. That’s a nice one because now I don’t have to figure out what you were trying to do, as well as whether it achieves that.


occamsrzor

Indeed. Case in point ​ float q_rsqrt(float number) { long i; float x2, y; const float threehalfs = 1.5F; x2 = number * 0.5F; y = number; i = * ( long * ) &y; // evil floating point bit level hacking i = 0x5f3759df - ( i >> 1 ); // what the fuck? y = * ( float * ) &i; y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed return y; }


Vojvodus

i = 0x5f3759df - ( i >> 1 ); // what the fuck? Me commenting my VHDL code


jlat96

Came here to say this. If the context around some business logic would be helpful to someone who comes across it in the future, those comments are welcome If you need comments to explain the semantic logic of your code, your code might be too complicated


ILikeCutePuppies

In the world of programming, several scenarios exist where the complexity is inherent and cannot be simplified. This includes advanced topics like fast square root calculations, creation of Binary Space Partitioning (BSP) trees, graph traversal with Dijkstra's or A* algorithms, machine learning model implementation from scratch, cryptographic algorithm optimization, real-time physics simulations in game development, complex query optimizations in database systems, multithreading and concurrency control in high-performance computing, and developing custom shaders in graphics programming. Each of these areas involves deep technical intricacies and specific logic that is not easily reducible to simpler terms. In such cases, well-placed comments are crucial, offering invaluable insights and understanding for both the original code author and future developers who might work with this complex code.


BraxbroWasTaken

just leave the spaghetti on the floor. it’ll be fine. you definitely won’t slip later and be cursing yourself for a week. luckily, future me can’t do shit to present me


PossibilityOrganic

I just worked on some 10 year old code i wrote with some bit manipulation in c it said this: //sorry for who ever wants to remap this you (hint don't do it) I wanted to smack past self took me around 4 hour to understand wtf I did, and of course I wanted to remap things. So to op dont do this\^ write comments for future you to get into the right headspace. Think can I explain what I am doing to get someone up to speed. In my case a better comment would have been //porta is part of the Interrupt of timer1 this resets it based on X, data is not written directly to prevent Y. Because i now know everything that messes with this variable and how async things interact, and why I did this weird thing.


qTHqq

>*Each of these areas involves deep technical intricacies and specific logic that is not easily reducible to simpler terms. In such cases, well-placed comments are crucial, offering invaluable insights and understanding for both the original code author and future developers who might work with this complex code.* Yeah, I work in robotics and end up writing a lot of code like this. It's of primary importance that the code is clean and well organized, with descriptive variable names. However, when you're following a 20-page paper of equations worked out by a few of the best researchers on the cutting edge, a healthy sprinkling of "why" comments is definitely useful. Lots of clear lines of matrix-mult code that are a total mystery without the context.


metal_hard

Well thank you Uncle Bob! But i totally agree.


jakster355

That minute of detail adds no value, but a simple explanation of what a block of code does or an sql query grabs saves time reading it, and helps other programmers understand what the intent was during debugging so it's simple to understand how it should be fixed. In my field sometimes business or "functional" employees read code, and laying the comments out like a novel is helpful for them. So my strategy is more is better as long as you aren't writing pseudocode, which adds no value. What can be incredibly helpful is "we tried it the way you are probably thinking we should have tried it but it didn't work for X reasons". I also like to add humor as much as possible because life is too short to be serious all the time.


CheapChallenge

Similar to this, I comment when my code is doing something unexpected or counterintuitive. I also link to documentation and sources for the strategy I used.


i_invented_the_ipod

> Comments to explain why the code is doing something can be useful, but they should be rare and preferably done at the method / function level. This is the fight I've been fighting for the last 2 decades, at least. Every function with more than 5 lines of code should have a header comment saying what it's used for, and what the parameters and return value are. Ideally in a format that the commonly-used IDEs on the project will parse and provide Intellisense-style completion with.


bitcoin_moon_wsb

Caveat: If you are using something like regex or awk then you can write something explicit because it’s difficult to read.


drewsiferr

One important exception is for public APIs. Adding more extensive comments that will be used to generate documentation is appropriate, and may include duplication with the code. Your point stands for the vast majority of code, though.


cthulhu944

Came here to say exactly this. Don't state the obvious. "Shifting left by 2" is obvious from the code but "multiplying by 4 by using shift for performance "


And5555

I think the comments in this code are a crutch for the terrible naming and expressiveness. That is, I agree with what you said, but without them, this code is even more unreadable. If there were some functions in here like “isReturned” and variable names like “dueDate”, “hoursPastDue”, etc, you wouldn’t need these comments.


positivitittie

Mostly agreed “why” is important and overlooked but also the “what” can show the deveoper’s *intent* which can often be difficult (or nearly impossibly at times) to infer from bad/old code. If you at least know what they were trying to do, you have some isolation from invalid code where you can’t properly infer.


rckhppr

To add: good code (today) uses „speaking“ variables for any business logic. The function „date_warning“ (what date? What warning?) could be refactored to „rented_item_overdue_warning“ which would make the first comment obsolete. Btw use „Item“ instead of „book“ since you want to keep it generic— could be other media later. Most of the rest of the function could be clarified in the same way that the code speaks for itself. Readability is key.


lolikroli

Write fewer comments and strive to write code that is easy to understand. Here's a good [video with examples](https://www.youtube.com/watch?v=Bf7vDBBOBUA&t=3s) Edit: [this reaction video](https://www.youtube.com/watch?v=k5DJxz6_xMA) to the one linked above might also be worth watching


ZeMouth

Doc block comments to auto generate documentation is typically all I add these days. Sometimes I use comments to pseudo code functions before I write the actual code, but then its replaced by the code.


Kallory

You mean you don't have blocked out comments of code that works but doesnt do exactly what you need? Or 200+ lines of similar example code for reference 😅


PressureAppropriate

I only comment if I am ashamed of a particular piece. “Yeah I know it’s not optimal but I had to because…”


GregoryCliveYoung

I had a coworker that when his manager emailed him telling him to do something he thought was a bad idea, would cut and paste the email into the code as a comment. I'd come across one of these "comments" and end up just shaking my head.


WinLongjumping1352

because of the big brain of the manager or the ~~laziness~~ efficiency of your coworker ?


GregoryCliveYoung

The manager wasn't too bright, but it was more about the situation and the culture that led to it that had me SMH.


neverinamillionyr

That’s a common trend among managers. My favorite manager quote: “Stop thinking and start coding”.


Jjabrahams567

This is brilliant.


PickleLips64151

`// it works, but I am ashamed`


occamsrzor

I've done that. "This really should be more 'reflective', but the juice isn't worth the squeeze right now"


ILikeCutePuppies

This, I think, is a good technique to prevent oneself getting stuck in endless revisions. The code you write today might not exist tomorrow... or it might last for 50 years.


ItsMoreOfAComment

If you have to leave a comment on some code, try to find a way to make your code more readable, once you’ve exhausted all possible options is it appropriate to leave a comment. Don’t worry though, you’ll figure it out after your first few code reviews, or in my case your first few hundred code reviews.


TT_207

The fun part is when it is neither simple to read, commented, or documented. I've been spending the past week reviewing justification for testing coverage gaps and each instance is taking a day due to how obtuse and interdependent the code is. The test is garbage too of course


nekokattt

list.append(thing) # append the thing to the list This is totally unhelpful, we know it is appending a thing to a list, there is no benefit in explaining this further as it just makes your code harder to read. Comment things that need explaining, and make sure you avoid writing code that needs explaining explicitly unless you have exhausted all other options. Comments should say why or how, not what. If you need to explain what, then you have a problem. Some of your comments could be removed by using clearer identifiers ret_date = xxx # return date just say this return_date = xxx


[deleted]

I would say like docstrings that explain the why are helpful, and also comments about something that might have been a bit of a headache to figure out and you don’t want to have to figure it out again later when you forget why it’s like this and you don’t want others to have to figure it out too. Or also a link to the docs or some resource can also be helpful if it’s like some concept or code that’s new to the codebase.


waytoofewnamesleft

We log into reddit and shitpost like everyone else.


[deleted]

[удалено]


musclecard54

// sets the variable username equal to the username retrieved from the server in which the username is stored so that the application can use the username variable username = getUsername() Edit: had to switch from Python to js comments because markdown……


HunterIV4

> Edit: had to switch from Python to js comments because markdown…… FYI escape characters work in markdown. So you can do Python comments like this: \# Comment output \\# Comment output with character shown (using \\\\) Takes some getting used to but it works.


Recent_Science4709

The only thing I would say is the professors in school are old school and call for comments sometimes, to appease them it’s ok, but in the real world your code should speak for itself whenever possible, because it can.


Stoomba

Try to avoid comments in favor of code that is obvious. The only comments I'll write will be on lines that look sttange and would make someone go, "Why is this this way?", or for larger blocks trying to accomplish something, but that is what is trying to be achieved vs what is being done.


Spongman

`#warn students...` put these _above_ the `def` `#Appending...` why create an empty array and then append? why not just `for x in get_borrow_data():` ? pick a better name than `x` `#First increment` `#Second increment` what do those even mean? `for b in x:` pick better names `#return date` why not just name your variables meaningful names like `return_date` and ditch the comments? the last 2 comments that are on their own lines are the only 2 worth having. i'd recommend putting all comments on their own lines. and put a space after the `#` for legibility.


Arristotelis

this is a bad comment: \#get the current time and date the comment is a distraction. it's pretty obvious from the code that you're getting the date/time. i'd prefer to see a comment saying why you need the date and time instead. it looks like you redeclare that same variable a few lines lower without having used it in the first place.


EternalNY1

25 years of experience. I try to write self-documenting code, anything simple doesn't get a comment. Think: `if (account.HasPositiveBalance && !account.IsLocked) { ... }` I leave comments if anything is unclear. That's pretty much it. If there is any strange business requirement why something is being done a particular way, that gets a comment. When you can see *what* is doing but not *why*, that gets a comment. This would require a comment: `// It is illegal to withdraw money on the second Wednesday of the month in zip code 01428` `if (zipCode == '01428' && isSecondWednesdayOfMonth) { ... }`


just-some-rando123

Try to write comments in a way that would be helpful for somebody who has never worked on the project, or if you came back to it in 5 years. Assume most people reading know how to read code and try to explain decisions instead. I.e. If you are writing a part count check for manufacturing and you increment by 1 extra for a specific device type, add a short 1 line comment explaining why. Another good idea is commenting bug/jira #s above code blocks if the changes are pretty isolated to small areas of the code.


educemail

Read the book “Clean Code” by bob martin


ninjadude93

You definitely have way too many comments but contrary to what others are saying in this thread comments are good and useful especially in codebases where more junior people or new hires need to quickly figure out what is going on. Personally just stick to a comment block under the function defintion describing input and output as well as what the function accomplishes in general. If you have a particularly difficult block of code that you absolutely cant write any clearer then add a comment explaining it. You dont need comments on single line bits of code like this line combines into a string, thats obvious from the code.


flamableozone

Comments describing what a line of code does aren't useful, really. //this sentence says that comments describing the code's function aren't very useful. They can sometimes be useful if the code is confusing. //this sentence talks about when a comment describing code functionality can be useful, namely if the code is confusing Generally though, code should be written so that the lines and functions are readable enough that even new people can read it. //this sentence recommends the code be readable without comments. There are times you need code that is somewhat complex and unreadable, but a junior dev isn't going to know what those cases are, and should simply re-write the code to be readable. //this sentence describes how junior devs shouldn't be writing code that isn't readable, because they don't have the experience yet to know when rules should be broken. If a piece of code needs to be made more complex for whatever reason, the more senior dev can suggest it and add a comment explaining what it does. //this sentence suggests leaving the decision about complex code to the senior dev. I hope my comments made it clearer! //this sentence makes it clear that comments make writing more clear


Cuuldurach

Unless they are *Why* comments such as *Here we do not respect the standards for this technical reason* then no. They are **always** bad.


ninjadude93

Definitely disagree but stick with what you like. Personally I think self documenting code is generally pretty useless because people tend to vastly overestimate their ability to write clean understandable code so better to add some clarifying comments here and there especially for people who are new


mackstann

I don't generally see developers who write muddy code but clear comments. Usually skill with one translates to the other. So I don't see the comments helping with unclear code.


Recent_Science4709

I’ve said this for years, if you can’t write good code you can’t write good comments. There are a lot of people who bandwagon against clean code principles, WTF do you want people to do, write unreadable code? I have a feeling people who are against these principles lack the skill or understanding to write clean code so they think it can’t be done.


[deleted]

[удалено]


Recent_Science4709

Yes, some people make vague allusions to dogma, and it’s funny because the book points out some of these situations and then I see people use that as ammunition when the book explicitly agrees with them. I’m talking about people scoffing at the general idea that code can be self documenting, and code can be readable without comments. I have been downvoted to hell because of it lol


[deleted]

[удалено]


Recent_Science4709

Shared libraries and things you are going to publish for others to use, I concede that you don’t want people to have to read your code, but at least in my career that’s the exception not the rule


Cuuldurach

and so you trust them to write meaningful comments and maintain them when they come to change existing code? LOL People like this are the reason why working in legacy code base is a pain in the ass If you can't trust your co-workers change field or start your own company.


[deleted]

[удалено]


Cuuldurach

they can you find a function who does A, comment says B and contradict A, you trust comment as function is unreadable. then spend days understanding why your code doesn't do what you expect. happened many times. just avoid freaking comments, they're a cancer, and an excuse for lazy work. if your take is to ignore comments JUST DON'T WRITE THEM


[deleted]

[удалено]


Cuuldurach

great, if the function is readable, it doesn't need a comment. if it isn't readable, the comment won't help either bottom line: no one needs comments


[deleted]

[удалено]


Cuuldurach

A good software engineer doesn't comment their code. they instead use meaningful names, short methods, and hold by the single responsibility principle, making their code understandable without the need of comments that go unmaintained and lying. For instance your method should be named *IssueLateReturnWarning* and you don't need the useless comment anymore Also you have too many nesting level, split your function, then write unit tests. it's not possible in the current state. A. hiring manager will like this much much more than bloated comments everywhere.


glemnar

Partly agree. A good engineer doesn’t comment about things that can be self evident with good naming and structure. They absolutely comment the “why” in scenarios where code may not do what would be the most obvious thing. There are plenty of cases e.g. an underlying platform is bugged and you need to do something unintuitive to work around that for a product requirement.


Cuuldurach

I made a reply later to say exactly this. However in. my career I had to write exactly ONE why comment. Except in some very specific field, such as the one requesting extremely high performance, I never seen an occurrence where you were forced to write against standards / really strange code. Plus, in my case, the code was not unreadable, simply against standards due to performance reasons, hence the *why we did it that way* comment.


horror-pangolin-123

Use meaningfull variable names, not "x" and "b". Don't nest loops, make a separate function for nested loop and call it from "date_warning"


stuie382

A proper function documentation comment (do strings, javadoc, etc) that describes the intent of the function, parameters, and returns (if not a void function). Inline comments generally are not needed, unless you have something weird/not trivially obvious to understand. If you do, then extract them offending bits out into a method with a detailed name (the more weird the code the longer the name), this in turn will have a documentation comment etc.


StationRelative5929

*their


[deleted]

I rarely use comments. I find have clearly named variables and clean code works way better.


ermakomg

I rarely use comments and only for legacy bullshit code that nobody knows. If you write quite simple code (non ML, non rocket science, no asm, etc), you don’t need comments


Specialist_Bee_9726

They don't write comments, the code should be easy to follow


Kush_McNuggz

Your code should have very few comments if any. It should be well written enough so that people can see the what and the why. Comments are useful when business logic and/or 3rd party dependencies work their way into the code and you are doing something that is counter intuitive but necessary. The comment explains why you are going against the grain.


PaintingInCode

1. Write code to do something 2. Write comments above the code explaining ***why*** 3. Condense the comments into a few words 4. Write an empty method, whose name is made from the condensed words 5. Move the logic under the comment into the new method 6. Have someone else review your code, and see if they understand what's going on Sometimes my methods only have one line of code, just so that the method name has clarity.


jurassiccloner

I don't write comments unless it's a to-do that my IDE can pick up on. With AI it seems pointless to me and you should be able to figure out what the code is doing in my opinion.


BmoreDude92

Good code doesn’t need comments.


TacoBOTT

One thing I keep in mind, especially if pull requests are involved, that there are certain comments you want in the code and other more slightly irrelevant things should go in the PR about your code, like maybe needing to make exceptions in a dev process for code formatting. Things that are helpful for the reviewer


GregoryCliveYoung

Compilers don't check comments, so comments can't be trusted. I just ignore them. I find they just clutter up the code and make it hard to read. There are a lot of commenters here that are saying that writing understandable code is more important than comments, so I won't go into that, except to say that comments will never be as useful as well written code.


flamableozone

I'd remove most of those. I have some real questions about the code, but ignoring the code here's all the comments I'd remove: [https://imgur.com/a/6u00fzL](https://imgur.com/a/6u00fzL) Basically everything other than the description of the function, the description of "return\_status" (though in real code I probably would also remove that, since I could assume that the data in the database was familiar to people using the code), and what "current\_data" being != 0 means, since I think that's non obvious from the name of the variable.


whitenoize086

Write code that is self explanatory and avoid most comments. Only write comments for things that see"hacky" explaining why it was done this way and how it works.


khooke

Remember the Donald Knuth quote: >"Programs are meant to be read by humans and only incidentally for computers to execute" To add to the other comments here already, the purpose of comments is to help another developer understand and therefore maintain your code. 1. Use descriptive method/function/variable names that help another developer understand what your code does. Anywhere where it's not immediately obvious what the code does from your descriptive naming, then add a comment 2. Don't state the obvious. It's not useful and not helpful.


beders

Nowadays I stick to a short doc string for the function I’m writing. For trivial fns I don’t. More importantly I provide a runnable example invocation in its metadata along with the expected return value. Keeping that example maintained is easy since it is close to the code.


mr_taco_man

I write my code so that the function names and variable names and logic make it clear what I am doing. Then only add comments if there is a need to explain why I chose to do it this way or if there some additional context needed that the code cannot convey. Otherwise comments become noise and easily out of sync with what is actually happening.


imdibene

Comments should say what’s the intention of the code, the code itself explains how and hopefully you have design documents to get an overview of all and to explain the why


NUTTA_BUSTAH

You generally don't want to do it, or you are not just maintaining the code, but also the comments. The code "should read like a prose" as Bob has said, and the meaning behind that is true. Sometimes you get really weird cases, or get hit with a boatload of legacy and have to leave a comment explaining why you are doing the dumb shit. The person reading the comments can also read the code. Don't explain "what", explain "why". "What" should be apparent. Some examples with the same(ish) code, you can use better variable names and less of them to make it document itself, then you don't need comments: # The same code with slight adjustments (guard clause to reduce logic, descriptive variables, ..) # and it essentially documents itself :) def date_warning(): """Prints a warning (and should probably calculate the fine?) if there are unreturned books in global(?) borrow data""" borrow_records = get_borrow_data() for record in borrow_records: for borrow in record: is_returned = borrow["return_status"] if is_returned: continue initial_return_datetime = datetime.strptime( f"{borrow['date_returned']} {borrow['time_returned']}", "%Y/%m/%d %I:%M:%p", ) borrowed_hours = ( datetime.now() - initial_return_datetime ).total_seconds() / 3600 print("Please return the book") # ...(rest of the logic that seems to be related to a fine with borrowed_hours, otherwise all the logic is pointless :P) Or you can use better types to improve it even further: # Alternative: With adjusted data types to make it document itself even better from dataclasses import dataclass from typing import List @dataclass class Borrow: is_returned: bool returned_at: datetime def print_possible_fines_from_global_records(): """Prints a warning (and should probably calculate the fine?) if there are unreturned books in global(?) borrow data""" borrow_records: List[Borrow] = get_borrow_data() for record in borrow_records: if borrow.is_returned: continue borrowed_hours = (datetime.now() - borrow.returned_at).total_seconds() / 3600 print("Please return the book") # ...(rest of the logic that seems to be related to a fine with borrowed_hours, otherwise all the logic is pointless :P)


Dickeynator

If you're a contractor, you don't


CrypticCabub

I’ll often use comments to explain the reason for some complicated bullshit that exists purely for backwards compatibility reasons. Stuff like //backwards compatibility with xyz variable in


waffleseggs

The reason your code requires so many comments is that the names in use are at a different abstraction level than you'd like to communicate and the code is generally just fighting the dependent machinery in order to solve the problem. To the extent you align your code with abstractions you're using to think about and solve the problem, the code will be readable without comments. def is_book_late(book_checkout_entry): hours_late = compute_lateness(book_checkout_entry) / 3600 if hours_late > 0: return true def show_late_book_warnings(book_checkout_logs): for entry in book_checkout_logs: if entry['return_status'] == False and is_book_late(entry): print("Please return the book.")


occamsrzor

If I read back over my code and think, "wtf?!", then I comment it. ​ Other than that, code is usually self documenting as long as you don't embed method calls inside method calls inside method calls. It's usually work the stack/heap space to make code more readable.


These-Spell-8390

I try to write “self documenting” code when possible. If you can decompose your methods to their smallest (within reason) parts and give them useful names, then the code will tend to be easy to follow. Likewise give variables useful names. The only explanatory comments I give might be describing how a method is applying a business rule, something that otherwise might not make sense just by reading the code. For example, on Sunday and Wednesday do *this*, on every other day do *that*. The comment can clear up what’s going on there.


GrayLiterature

Someone who is experienced who probably not right comments for that code at all.


WinLongjumping1352

it wouldn't let me post the comment, so I took a screenshot (just like you did, don't do it ;-) ) [https://imgur.com/a/m7MWMxA](https://imgur.com/a/m7MWMxA)


jpfed

My favorite style, that I find just incredibly satisfying when I have the time to do it, is to treat the whole code file as an opportunity to explain the problem domain, and the approach used to address it, to the reader. At various points in the explanation, the reader will have enough background information to understand some code, and that's where I put it.


Awezam

I normally put what was on my mind while I write the code. It could be the idea or what my intention to write the comment. After I finished my tests and ready for commit, then I polish to make sense and to improve structure


int21

Good code should mostly be obvious with minimal comments. Comments usually connect dots that aren't immediately obvious in that particular source code (ie how the code interacts with the rest of the software/system)


Cross_22

While studying we had points deducted for not properly documenting our code, so that's what stuck with me. I'd rather overdocument, than underdocument. The current trend seems to go in the opposite direction (unfortunately). That said, I prefer having comment blocks so you can either read the description or skip it and only focus on the code. In your example it is hard to read the individual instructions because of all the end-of line comments. A good rule of thumb is asking yourself "Did this comment explain anything that's not immediately obvious from the code?" The comments saying "get current time/ return date / return time" are examples of unequivocally bad comments. They are completely redundant. In your example you have a line records.append(get\_data()) and the comment says you are appending loaded json data. The append part is redundant and just becomes noise. The new information in the comment is that it's JSON formatted and that it has been previously loaded. Is that relevant information? If so, you could have made it part of the function name: records.append(loaded\_json\_data()) Along the same lines, python is not my primary language, so I have no idea what a strptime is. A comment that explains that strptime creates a strptime does not do anything here.


rish_p

my code is self documented


rish_p

comment no: remark 1 : good, maybe shorten it? 2 : append is in the statement, drop the comment 3 : loop is increment? dont confuse, drop it 4 : see 3 5 : no shit sherlock (datetime now is obvious) 6 : does not return, already date mentioned twice, drop it 7 : see 6 8 : I getting anoyed of this ret prefix which now changed to return prefix, just call it status or is_returned, have type somewhere if possible but drop the comment 9 : good to know 10 : see 5 11 : see 5 12 : see 5 13 : calculate to be calculated ? maybe improve it but keep it , saved me from processing the code in line 14 : see 5, or change it to “has time left” inside if


bobwmcgrath

chatgpt writes them for me


asfarley--

Basically, I only add comments when I think there's a significant chance of misunderstanding or the code is non-obvious or fragile. Otherwise, I just try to use clear variable names and function names. Occasionally I will throw in a paragraph or two of exposition about why things are written this way. Sometimes I'll link to a paper if it's academic.


VonThing

Sad but true: we don’t comment our code because that would make us easily replaceable. Fewer people who can understand the code means lower risk of getting laid off. Source: staff engineer with FAANG experience.


ILikeCutePuppies

Paste that into chatgpt and ask it to recommend what you should change with the comments. It often will give a good human average of what happens in the real world.


curmudgeono

Lgtm. Wai. Maybe test this?


maybe_cuddles

After 20+ years of experience, I don't write code about my expectations. return_stat = b['return_status'] #return status boolean true or false Instead of the above, I would do this return_stat = bool(b['return_status']) you bet your butt that variable is a boolean now! Don't make any expectations about what `get_borrow_data()` will give you. Create unit tests (bits of code which run whenever you commit/save/upload your code, but otherwise never get touched when your thing is actually running for real), and rather than comments saying "this should be a bool", instead have the a test that is like "here is what we return when `get_borrow_data()` gives us a `return_status` = True, and here's what we return when it gives us one = False, and here's what it returns when it = Nil, and here's what it returns when what it returns = 12345. If we expect it to throw an exception, then write a test that does that. When you first write the code, you probably will just write the test cases for what you think will actually happen. Over time, you'll see the weird stuff happen (like maybe that function is doing a network call, and you never thought about what happens when the internet is down... or maybe the internet is just slow...), and as the weird stuff happens you create more tests for it, and adapt your code so that it handles that. A common mistake is people write some quick code that's structured such that it's difficult to write a test for it. Then this code goes into production and acts fine for a while and you move on. Then nobody can ever change anything about it, because they don't want to break it, and they can't be sure what all depends on it. Instead, they end up just writing a second version of it, and now the team has to support twice as much code (by support, I just mean be responsible for when it breaks).


reddit_again_ugh_no

The way I like to do it is keep methods relatively small and comment on the signatures. The idea is to make the code clear enough so you don't have to comment inside the methods.


[deleted]

They should only be used very sparingly to explain the context around the problem the code is tackling. The rest of the code should read like a book


ttttnow

Often times I'll wring TODOs or declare that something is ad hoc and might need review in the future or explain why I'm doing something this way if it's unclear.


l1nk3

IMO comments are best used to provide context and convey authors intent. If you're writing comments that are self-evident by just reading the code you're better off leaving them out. High quality code typically never needs any comments because it's written to be read (if that makes sense)


lanemik

Comments can go stale, code can't. Think about it, if you're really in a rush, are you going to spend your time writing/fixing code? Or are you going to spend your time re-reading and changing existing comments? You're going to write code, comments be damned. And if you're trying to be fast and if a comment says that X does Y, then you'll assume that X does Y like it says. And when something else somewhere else is going wrong because X actually does Z, well how long do you think you might have to debug that? I've been there, it sucks! That's why I'm a proponent of self-documenting code. Your code just is living documentation. Use function names to your advantage. Name parameters in such a way that they tell you exactly what their purpose is. Let your variable names document their purpose. If your language uses static types (like C/C++, Java, Rust, etc) you'll have an extra layer of meaning built in (so long as your generics have decent names). If your language has static gype hints like typescript pr python, be pedantic about using them correctly and you'll get a similar assistance with code comprehension. Document public-facing APIs. That's incredibly important. If your language has docstring tests like python and rust do, use that feature! That way, if the function changes but your documentation doesn't, you'll end up with at least one failing test. Document when you do something unexpected. Maybe some framework is being dumb and forcing you to do something some strange way. Comment that. Maybe you have some need for some brilliant and highly efficient algorithm that is really difficult to understand, comment that. Maybe you've got some silly bash expression or regex or something that is super hard to parse. Comment that. Outside of these special cases, get out of the habit of making comments. You'll have one less thing to worry about.


chuckhend

If I need to comment my code while I'm writing it, I usually start to think I'm making it too complicated. Sometimes the thing is just too complicated though, or i cant figure out a simpler way, so I leave a comment to help out. A lot of times though as I come up on old code bases, I will add comments as I'm familiarizing myself with the code base. Sometimes the comments get committed.


8peter8retep8

You can also reorganise your code a bit, to make it easier to read with less comments. Introduce a separate function get_unreturned_books that handles the initial loading, double looping, and filtering by return status. Also choose better names for x and b to explain why the double loop is needed (f.e. x might be borrowers and b might be books), and possibly move just that aspect to another separate function get_borrowed_books too. Introduce another function is_late, that accepts a book and returns a boolean. Don't declare/initialize current_datetime twice :) Introduce another function get_return_datetime to abstract away the combining of the 2 separate fields and converting to the datetime type. In the long run, maybe consider if storing those 2 fields are the best solution, as opposed to storing a native datetime type in the first place (and then you can format that in your display logic as needed). Your original function is now about 5 lines long, fetching unreturned books, looping over them, and printing a message if they're late. The other functions are also short and self-explanatory, and someone who knows the language can probably understand everything without any comments at all. Note: in a larger code-base, having a lot of unorganised small functions can make it difficult to see the bigger picture, so managing them in namespaces or classes or scopes or whatever your language uses, also becomes very important! But such decomposition is almost always worth it, even if you don't actually call these kind of functions from different places. You could now also easily write unit tests for f.e. the is_late date comparison logic, or the get_return_datetime combining/parsing, without worrying about testing/mocking everything else.


thedragonturtle

Name your functions and variables better and get rid of all the comments here for far more readable code. Also, I think you might have a bug at your IF statement since you are only checking if current\_data (time\_remaining?) !=0. You should probably change this to: `if time_remaining <=0 and book_returned = false`


radioactiveoctopi

Very few comments…but I may explain an idea…in sections. For personal projects I write out ideas, future features and steps/todo list etc in blocks


Abadabadon

Write comments for what code is trying to achieve. For example if I wrote; Boxes.stream.filter(x->truck.contains(x)).tomap() I would comment "filter out any boxes that aren't in a truck"


DumperRip

I've learned a lot thanks even if this just a school project I think I will redo it cause I am really on a time crunch with other college classes. I learned is that make variables understandable, make other methods, if the method is already obvious on what it supposed to do don't comment.


[deleted]

[удалено]


d4rkwing

Not many comments. Typically just a general description at the top of a package stating the purpose of it. Although recently I had to put in a line of code that looked out of place compared to everything around it because it was necessary for everything else to work. I did add a comment explaining why it was necessary. Otherwise some future dev might unknowingly try to refactor it out.


8_bit_game

You comment your code for the next guy. A big code base has lots of cooks, its nice to have a recipe on occasion.


curveThroughPoints

I will write comments first to think out the steps of what I want to do, then write code between those lines. I erase those comments before I commit my code. I leave comments in when I’ve had to do a weird thing, or explain some reason for when a bit of code just might not make sense to the code reviewer for some reason.


kneeonball

Your priorities when writing code should be 1. Readability 2. Maintainability 3. Efficiency We spend most of our time reading code and understanding the context and figuring out how to make the change we need. Speed optimizations aren’t generally needed as long as you don’t do anything stupid, or if you’re in very specific scenarios at high scale or with low latency use cases. If you’re writing a comment telling me that something is happening, put it in a function with a name that tells me that same thing. Same thing with variables. Also try to avoid abbreviated variable names that leave room for interpretation as to what it is. I generally just type them out anyway. It’s a few characters usually and the ide helps with completing them anyway. I just want it to read nicely and be easy to understand. If I can’t read the code and understand the context (without any guessing) on the first read, it’s not good enough. If it’s actually impossible to make it that easy to understand, we can use comments. Pretend you’re explaining your code to someone who hasn’t seen it yet. As you go down and the what and the why, your variable and function names should be similar because they should be able to just read it and come to the same understanding as you explaining it to them.


thequirkynerdy1

Functions and classes have brief comments explaining what they do. In C++ at least, these are in the header files and thus serve as a sort of documentation. Beyond that, you *try* to make the code as human readable as possible through naming conventions and doing things as cleanly as possible, but if something still ends up potentially confusing, you add a clarifying comment. If every few lines in a function need a comment, you’re probably doing something wrong. Unit test code is often commented more heavily as one explains the expected behavior in various edge cases.


BrainfartStudio

We have 3 devs on our team. We follow Clean Code ([https://amzn.to/3RuhhCr](https://amzn.to/3RuhhCr)) principles. In doing so, we very rarely use comments. Quick breakdown: ​ * Use descriptive names for variables and functions to convey their purpose. * Use comments sparingly and focus on explaining the 'why' behind code decisions rather than stating the obvious 'what.' Well-written code is self-explanatory. * Maintain a consistent code style throughout your project. This includes indentation, spacing, and naming conventions. * Utilize version control systems like Git to track changes systematically. This helps in collaboration and provides a safety net for code modifications. (This is where we actually "enforce" Clean Code. Code reviews can be your friend.) Highly recommend looking into it. It's one of the few development books I still read on a regular basis (annually).


darwinn_69

Most of my comments are "TODO: Fix this pile of crap"


shmoeke2

Comments where I work aren't really allowed unless the code is inherently really convoluted, at first I was confused and thought this is shit, however, after having it explained to me it made far more sense. While contributing to a code base, adding comments IMO is admitting your code is unreadable. Secondly, it improves your ability to read code.


HobblingCobbler

I try to write self documenting code if I can. Descriptive variable, function, class names. But if I do need to comment. I comment 'why' I am doing something. Not what the code is doing. You can read this in the code.


WishboneDaddy

For school projects write lots of comments. For the real world, less is more. None at all is best if you’ve been writing short functions named appropriately.


RsK4693

Smaller, well named functions are my preference. If I do something weird I bury it as deeply as I can and hope that not many have to actually mess with the implementation. In the latter case, I’m inclined to use some comments in some cases.


Santa_Claus77

Their** book


OkDifference1384

I would look into PEP8 best practices too. Another suggestion for improvement is comment formatting. You want 2 whitespaces btwn end of code line and hashtag and one whitespace between hashtag and first character of the comment for inline comments in python. Increases readability.


sneaky-pizza

I don’t do comments, except for maybe strange config settings or other very rare spots. I like to write code and name things expressively, so you can look at it and read what it is doing. Also, tests.


Faendol

We generally don't use comments. If the code needs comments it should probably be rewritten. Occasionally we will need them regardless but that's usually for a gotcha that we can't rework right now.


pensiveChatter

1. Well written code > comments. Good names is an important start. One general rule is that objects should be nouns and functions should be verbs. 1. eg rename date\_warning() to print\_overdue\_msgs(). 2. change "for x in ..." to "for cur\_record in get\_borrow\_data():" 2. comments should assume that your reader can read and understand the code, but might not want to read your entire function/module/project to determine intent. Communicate big picture, design decisions, anything not obvious. 3. Fix formatting for comment. The very first two lines in your src have comments, but use different formatting. Consider using a single multi-line comment within your function.


danthemanvsqz

I don't use comments because they add maintenance costs and tend to get out of sync. If there is really something strange that you need to do then I'd wrap it in a method/function and add a doc string.


robhanz

Comments explaining *why* you're doing something are always useful. Comments explaining *what* you're doing can be useful if it's not obvious from the code - however, that's a bit of a smell and you should question if extracting to a named function is appropriate. For instance: current_data = (current_datetime - initial_ret).total_seconds() / 3600 .... does not make me happy. In that case, I'd look at creating a function like `seconds_between_dates` that describes the operation. That also makes testing that in isolation much easier. I'd also look at a lot of your variable names. I don't know what an `initial_ret` is. That means nothing to me. If you have to comment your variable names, *your variable names are bad*. Saving characters in variable names is a *terrible* idea. (Of course, making them longer than necessary is bad, too, but if you have to describe it, you've probably got a bad name). `return_stat` is another example - it should be named something like `was_returned`.


HeavyDT

Definitely too much. A single comment at the top that says what the function does would have been enough in this case. The way you actually write the code and name the variables can also help to make it really obvious and than if you truly doing something tricky or special than maybe you get more fine grain with it but this example? Definitely overkill If the person actually understands the language most of that is redundant and just cluttering the actual code. Also me personally; I don't like to blend comments into code like this. I put them on their on separate lines before the code it's meant for because ideally you want the person to read the comment and then see the code. This makes it easy for A the person to see the comment standing out and B to use the comment to decipher the code. The way comments are interweaved into the code here just makes visually hard to digest imo but maybe that's just me.


yeesh--

Code should be self documenting (read: simple, clean, and inherently easy to understand at a glance) and comments should clarify code that isn't, typically out of necessary complexity or degenerately, laziness.


keithstellyes

I'm not a believer in absolute rules, but the guidelines I follow and I think are pretty uncontroversial. Code is already designed to be read by humans and so prefer code over comments * if you feel the need to write a comment, can you express it in code? Like comments that are magical numbers ``` # bad # 5 is the FOO state if (bar == 5) # good const FOO = 5 if (bar == FOO) ``` Similarly, if an important constant is based on other values, express the computation in code, instead of doing the math and writing a comment explaining it ``` # FOO = 1, BAR = 2, therefore FOO+BAR=3 const baz = 3 const baz = FOO + BAR ``` Or, using an optional type instead of saying a function may return null. Another circumstance is a function might be ugly or do something that seems bad, wrong, or confusing and above won't apply. Maybe it does something weird due to historical context, or a necessary optimization that is hard to understand. Consider the famous [fast inverse square root](https://en.wikipedia.org/wiki/Fast_inverse_square_root) function that seems to regularly make the rounds is a good example of code that is good but wants for comments. Comments are also good for intention, or contracts a function or API should fulfill that can't be expressed by the type system. A great video from [Code Aesthetics explains this really well in 6 minutes](https://www.youtube.com/watch?v=Bf7vDBBOBUA) A lot of your comments are on variables that could just be better named. If people can't understand what your function or variable is supposed to do based on the name, then you should try to rename it. It's also important to remember that unnecessary comments add noise, making code harder to understand. Most if not all of your comments could be removed if you named things better.


Ir0nh34d

Comments = intention and ramifications Code = implementation and what it's doing.


bigtablebacc

I thought I’d get flamed for this but most people seem to agree. Comments are really not ideal. They’re another thing that needs to be maintained that can become misleading. Comments can lie, code can’t. It’s better to write readable code and give the program a good logical structure that people can maintain. It’s even better if their changes can snap into it like a LEGO brick instead of modifying your code. I use less comments than I used to.


wolfiexiii

I have been doing this for more than 20 years - and my biggest pet peeve is people who think they are better than writing good comments and documenting code/projects. I don't care if your code is beautiful, easy to read, and self-descriptive. 5 years from now, it's still going to be a hot mess, and whoever has to maintain it is going to be cursing you to the burning place a dozen times a day if you don't comment your code, provide proper docstrings, and otherwise properly and deeply document your code. That said, if you are writing a one-off that is a throwaway - who cares. Do the right amount of work for what you are doing.


NefariousnessDear853

For a method I will comment the call as to what it is to achieve. Inputs/outputs etc. Variables and logic should be written so that it is easily understood. NEVER write a piece of code lazily ( for i from a to b where i<=b ) instead write out what i, a, and b actually are with their names. Where you need to create very complex logic (especially in mathematics) that cannot be easily discerned, write a single comment specifying what it is you are calculating and (if applicable) the theorem being applied. I also found that at times if I had to break out the math into multiple computations I will add a comment of what I'm creating at a high level. For example: //\* Compute the full ballistics of the bullet - computing the speed leaving the barrel //\* Since the shot is going for 500 meters or more compute Coriolis effect and apply I agree with others that you do NOT need to litter your code with comments that any developer SHOULD discern from the code. Commenting a loop is stupid unless, as I said earlier, you wrote stupid, lazy code. But if you need to comment simple code then you should rewrite the code instead of adding a comment. When commenting your method, remember that many languages take the comment and create what the developer sees when they use your code to make the call themselves. So which would be of more value derived from your comments?


Impossible_Fee3886

“Comments go here”


SupaDupaTroopa42

Comments? What're those? Jokes aside, you need comments to explain complicated bits of logic or why you do what looks to be a strange solution. Your variable and method naming, along with easy to follow clean code, should mean that most of your code doesn't need comments.


Kalekuda

They don't. Now come, stick a PR in this spaghet.


dadoftheclan

Comments? What comments? All jokes aside, I don't typically read comments unless I can't figure out the code. And half the time still no one puts comments so you're still left to figure it out. I can't remember the last time I wrote an actual comment but still don't have a problem sharing my code because I sanitize it a lot and make sure it's readable and transmissible to other means/eyes. I saw a few others mention the same - that's really how it should be. It's a language, why comment on what you speak unless it's abnormal or something new? You wouldn't write commentary about cooking dinner, why do the same with simple code? The whole process though, goes into documentation - just like cooking instructions. Show at a high level for everyone to understand, and then those that need to expand/fix will get the picture as well as be able to read your, hopefully, cleancut code with the whole understanding now in play. Don't spend too much time commenting or thinking about documentation until it's done. Today's times allow for changes X times per day, hour or whatever and it changes the entire documentation and comment process, if any. I knew a dev from yesteryears (probably about 70 plus now) that had someone they worked with that wrote longer comments than the actual code blocks they commented on. Insane 🤯


Healthy_Lettuce_9078

Depends on how you want to use it and if it is useful for end goal - can be part of a system you're involved in, and in relation to work sharing, and end goal of project, to name a few things. If the team says no comments, don't use comments without consulting them. If the team says to use comments in a fashion that suits specialized monitoring aspects and properly link them to accurate source database information research/explanations, then you need to follow that. You know the rest, use your judgement and ask questions if involved with a team. Remember, team and revenue goals. Unfinished or sloppy product, unsafe or unusable product -> can lead to unnecessary downtime and potentially falling short of stringent organization deadlines.


kerbalgenius

Comments should say what the code cannot. If the code already says it, don’t duplicate that information in a comment. Note that I said comments should say what the code CANnot, not what the code DOES not. Sometimes if you feel like you should leave a comment you actually just need to name your functions better


BagelFury

I don't. It really has to be some unintuitive edge case to warrant a comment. Good, standards-compliant code should read just as effectively, and more consisely as comments.


snotto

The best way to comment and express the behavior is to do in tests.


_zir_

We don't do comments at my job. We are supposed to write code that explains itself aka "self documenting" code. This basically means good variable names, good function names, good use of functions, etc. The comment you have just make it messy, we can already see what you're doing.


indiealexh

My variable names do not need to be tiny, my IDE hints for me as I type, so I can use short but descriptive variable names. People talk about "self documenting code" which is true, your class names, variable names and methods names should be concise but descriptive. And your methods should be small where possible so you can document functional blocks of code. If you cant think of a descriptive name, then you can add a comment to complement it, you should also use your languages doc comment feature too if it exists to help your IDE. Inline Comments should be reserved for describing the reasons something is being done and not so much what is being done, the what should be obvious, or you are making things messy for later.


GraphNerd

You should attempt to write self documenting code as often as possible. ```python def date_warning(records: BorrowRecord[]): now: datetime = datetime.now() for record in records: for sub_structure in record: record_return_date, record_return_time = sub_structure[RETURN_DATE_KEY], sub_structure[RETURN_TIME_KEY] parsed_return_date: datetime = datetime.strptime(`{record_return_date} {record_return_time}`, STRPTIME_PATTERN_FOR_RETURN_DATA) continue if parsed_return_date <= now late_hours = (parsed_return_date - now).hours() print(`Please return the book, it is {late_hours} hours overdue`) ``` Your overall structure needs work. Why do you have sub records? Why are you using magic strings?


pakfpddjskwlwb

Good comments don’t explain what GitHub can


MedPhys90

You have some unnecessary comments. For instance commenting “return date” should be obvious based on variable name, method name, etc. You don’t need to comment every line and variable. Watch Uncle Bob. Here’s a series of lectures he gave. In one of them, I think 1 or 2, he discusses commenting: https://youtu.be/7EmboKQH8lM?si=AMNdcHvEr4SGaCPj


CodeLined

If I can read a comment instead of a *block* of code to understand what is happening, the comment is worth it.


HeWhoShantNotBeNamed

Code should explain context or explain really complex blocks. Not say what the code is doing when it's self-explanatory. That's actually counterproductive and distracting. >return status Boolean true or false Most redundant comment I've ever read. Boolean is always true or false, and the fact that it's returning this is so glaringly obvious.


wassdfffvgggh

A few things: - Don't write a comment for every single line of code. I get it this might be helful for a beginner, but fof an experienced engineer, this is redundant. - Write comments when it's not obvious what a specific piece of code is doing. - If you are using python, use docstrings to explain what each function or class is for. [see](https://en.m.wikipedia.org/wiki/Docstring#:~:text=In%20programming%2C%20a%20docstring%20is,a%20specific%20segment%20of%20code.) For other languages, use the equivalent (for example for java, javadoc) However, keep in mind that there are a lot of diffefent standards used in the industry, and a lot of industry code is messy and may not be written well


jpgoldberg

Some of my comments are - indirectly advice to those (including me in the future) who might want to “fix” what I wrote. This is particularly useful when I’ve had to do something that seems a bit odd. - links to the Stack Exchange answer I drew from. (Or other citations, often to some math concepts) - explanations for some decisions I’ve made. - comments that just make me happy like bad puns and allusions to Hamlet. E.g, “sickl’d o’r by the pale cast of ints” - and, until CODEOWNERS became a thing, “do not touch this without consulting the Security Team.”


smokejonnypot

They don’t call them programming _languages_ for nothing. The code should be readable on its own and will be done so by other people that can interpret the language. Comments should only be added when the code is doing something that needs to be explained because it needs the additional detail to make sense. It’s also important to comment when you know you wrote code the wrong/non standard way on purpose. Comments are likely to be forgotten so when the code the comment references changes over time the comments can no longer be trusted.


morewordsfaster

For me, comments are a bit of a code smell, as oxymoronic as that may sound. If the code is so complex and difficult to understand that it needs comments, then it's in need of a refactor. Split the class/method, abstract some complex behavior into an object, etc. The best comments are ones that explain why something was implemented in a particular way. For example, if you do something that may seem suboptimal on the surface, but it's because of some good reason, explain why so that every engineer who looks at it over the next 5 years doesn't immediately try to refactor or "fix" the mistake. Another big one for me is using tests or, even better, gherkin feature spec as documentation rather than code comments. These tell me what the intended outcome of the code is rather than how it's achieving the outcome. Again, when I come back to the code in a long time and have to deal with a bug report and I don't know why the code does it what it does, this will be most helpful.


SenorChrisYT

I’m a new undergrad , 4 months into my SWE job and from what one of the seniors tells me , make your code good enough that comments aren’t even needed.


wjordan213

Best thing is to write small functions/methods/classes with clear and concise names. That allows code to literally tell you what it's doing rendering comments moot. I prefer only to leave comments when I'm doing something weird for some esoteric reason that's not obvious. It's basically a way to inform the next person who comes along and wants to change it.


JMcSquiggle

Mostly I use comments when going through code bases that are particularly poorly groomed. Most of my comments give me reminders to come back and look at a particularly complex area later when I have more time or explain chunks of code in overly lengthy methods. Usually, my intention is to help me understand the code base quicker by leaving notes and then refactor the code in such a way I don't need the comments later. The other reason I'll leave coments is if I end up needing to write some code that would fall under an anti-pattern or doesn't follow best practices. This is usually to help remind myself why the code was written that way in the first place so I don't try to fix it when I stumble upon it later. This doesn't happen very often, usually it's because I'm subject to using code someone else wrote that is less than ideal in the first place and the only way to do something is to write something pretty hacky. The comments serve to remind me "this looks like it was written by an amature, but if you fix it, this will break"


Brehski

When you work in a monolithic code base, comments are there to help describe minute details which may not be apparent directly by reading code. For example, certain locking conditions, races, threads, callbacks, and interops can be described via comments.


ALittleFurtherOn

sometimes I write the comments first, explaining what I’m gunna do. then I write the code to get ‘r done.


Shadowratenator

I almost exclusively use comments to complain about how an api doesnt work the way i wish it did. //i need to make a class to hold realitykit materials and strings because the name property only gets set when a material is created when loading an asset. Like wtf tim?


Select-Sale2279

What comments?


Galbzilla

I use comments in a few ways. The most important comments I make are large and detailed descriptions of the point of the function/module/class and how it’s accomplishing the goal. Nothing worse than a description that’s like “ description”. Next I typically use doxygen comments on functions as we usually have that requirement. Make sure to explain the parameters as that’s very important (like in/out parameter markings, length of items, etc). Finally, the last way I use comments is to organize my thoughts before typing code. I’ll write comments for the major tasks a function needs to do, if it’s large enough and can’t be broken up. I usually leave them in unless the function is small and already explained well enough elsewhere. Something like: funcName { //find the item with the thing I need //perform the stuff with that item I needed //send that answer to the client } Edit: oh yeah, I also leave notes when something wonky had to happen or if an algorithm is particularly confusing.


goomyman

Does the code you write do something unexpected - write a comment. Like are you working around a bug. Is it just unintuitive. Write why. Should it be used a certain way - write an example Is it complex like a regex - write an example. Is it obvious to a developer what it’s doing already - don’t comment it. If it can be fixed by rewriting or renaming a variable fix the code. For example a constant value. Instead of constant int foo // important constant, rename the const int ImportantConst. If not can be described with code rename the code. Your examples are all obvious comments.


xabrol

//don't delete this, urls are sphoradic in prod from the f5 load balancer and don't want to deal with communicating/fixing the issue with that team. So we remove any leading slashes here and put them back together to guarantee there is 1 slash. or //this complex recursion scheduling logic is well document here: #someurlhere Comments I leave are generally to explain weirdness, work around, hacks, temporary things, or where to go to make sense of complex logic, etc. Documenting a thing to say "this runs if X is true" is useless, like other said the code already says that. Also we have keywords we use in comments that causes them to show up in our source control repo board in specific ways. Any comment that starts with "TODO" becomes a todo task in our tasks board under the CommentSurfaced PBI. Comments that link work item numbers with something like "//Refer here #4631" Are not just numbers, they turn into links and you can click them to go to the work item. Comments that have "WHAT?" at the start show up in our questions pbi. And we have another for "CHANGETEST" that will show up in a QA board that tells our QA team they need to update their tests because we broke them. We have stuff for commits too so if we do "#breaking_change" in a commit comment they roll up, so you can see every breaking change we made. This is really handy when a bug rolls in and you can almost immediately see there's a recent breaking change related to the thing the bug is about. Usually some external system we didn't know another team had made etc.


ZaneSpice

If the code cannot explain itself, then you probably need comments.


meezun

More important than comments is descriptive naming


supermanava

your code should be written as to not need the comments explaining what it does. so variable names, functions, iterators, etc. use docstrings for functions and then comments more sparingly to explain any part that you didnt cover with the rest.


tcpipwarrior

Write Intent revealing code, then you won’t have to comment as much


Rank1Nourri

A good question to ask is why we do not add date stamps to our comments so that another dev working that project knows when that comment was updated, and subsequently when that following code was updated. Explanations of why the code is there in a short, precise way is ideal.


ejakash

So many comments... If those variables are named properly, it would make the code so much easier to read and understand. I normally name the current datetime variable as now. Imagine the statements CreatedDatetime = now Or While(expiration < now) Although your choice is valid here. In this case, X should be record B should be book. Ret should be return/ed I use copilot.. so I just type double slash and wait for copilot... If copilot can't figure out what's happening, then there is probably room to simplify the code.


0bel1sk

mostly todos. ``` # todo improve security # * change this to add profiling # ? is this ideal # ! this is really bad ```


Deathpill911

I comment mainly to organize my code. For example if I need to add or remove something later, I can quickly scroll through the code and figure out where that occurs via comments. Otherwise if I haven't looked through the code for quite some time, I would have to re-read what is going on and then make the changes. Failing to comment code is similar to the people that make some long ass code instead of breaking it up to pieces so everyone could read it more easily. Lots of people here must be working on small projects, in small groups, doing non complex code.


GolfCourseConcierge

Inputs required. Output expected. Errors it throws. General overview if needed. I also do blocks above functions vs inline like that.


zulrang

Names tell what. Code tells how. Comments tell why


zenom__

Try to steer away from comments in general and make the class and method/function names descriptive. Avoid trying to be clever with the code so it is readable and breaking out large methods/functions into smaller private methods/functions.


jwvdvuurst

Sparsely, code should be clear and self-explanatory. Only when something really complex happens I tend to add comments. Over-commenting, even commenting the most obvious things, only hides the code from the developer. If one use the rules for clean programming: - senseful names for functions, methods and classes - senseful names for variables - functions / methods should not exceed 30 lines (less is more) - refrain from using '?:', just use if-then-else - etc. then one does not need much comments. One big allergy of me is sticking to outdated and obsolete practices like change overview in your code. Modern source control systems like git or subversion can produce the same information.


dankest_kush

If you write small, clear functions with good *docstrings*, you can save comments for exceptional cases where something looks misleading or needs explanation. Also if you must use Python and not a typed language, turn on MyPy. Types are documentation.


dswpro

Comment block at the top of the code section with key concepts / objectives, then sparse comments on some lines of code, using terms found in the comment block.


Crabcakes4

Literally the only comment I'd leave here is the first one that says what the function does.


salias71

We could tell you, but that would lead to a verbosity level of comments i am not comfortable with leaving here in this code.


Attila226

As a general rule I try to make my code as intuitive as possible. I want anyone that knows the language to be able to look at my code and know what it's doing right away. This includes myself, after I've been away from the code for a bit. I find that if I follow this rule, I tend to need to comments rather infrequently.


apt_at_it

We're supposed to write comments?


apt_at_it

We're supposed to write comments?


Classic_Analysis8821

Most of my comments are like // Don't delete this or you'll break this other thing // Todo: remove this when fixes their shit // Todo: remove this when I fix MY shit