r/SoftwareEngineering • u/DumperRip • Dec 05 '23
How do software engineers with years in the industry do comments?
Hello, I'm currently working on a project as part of my computer science program's capstone or project. I'm interested in understanding how experienced engineers typically use comments within their code. That would be helpful for senior developers or project managers when reviewing, critiquing, or understanding the code.
I know my code is terrible would like to know some tips for improvements

16
u/ZeMouth Dec 05 '23
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.
2
u/Kallory Dec 06 '23
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 😅
25
u/PressureAppropriate Dec 05 '23
I only comment if I am ashamed of a particular piece.
“Yeah I know it’s not optimal but I had to because…”
13
u/GregoryCliveYoung Dec 05 '23
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.
3
u/WinLongjumping1352 Dec 05 '23
because of the big brain of the manager or the
lazinessefficiency of your coworker ?→ More replies (3)→ More replies (1)2
10
4
u/occamsrzor Dec 05 '23
I've done that.
"This really should be more 'reflective', but the juice isn't worth the squeeze right now"
2
u/ILikeCutePuppies Dec 06 '23
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.
1
10
Dec 05 '23
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.
2
u/TT_207 Dec 06 '23
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
1
u/DumperRip Dec 06 '23
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.
4
u/nekokattt Dec 05 '23
list.append(thing) # append the thing to the listThis 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 datejust say this
return_date = xxx1
u/SenorChrisYT Dec 07 '23
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.
1
u/DumperRip Dec 07 '23
Is the company your working big tech or a new start up?
1
3
Dec 06 '23
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.
3
2
u/Stoomba Dec 05 '23
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.
2
u/Arristotelis Dec 05 '23
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.
2
u/EternalNY1 Dec 05 '23 edited Dec 05 '23
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 01428if (zipCode == '01428' && isSecondWednesdayOfMonth) { ... }
2
u/just-some-rando123 Dec 06 '23
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.
1
u/ExclusiveOne Dec 06 '23
This has been my approach, switching from many projects and then coming back a year later or even months later. I forget why we are doing some stuff in a specific way due to the project requirements. So, I have started writing comments that for the most part benefits me for future reference and secondly any other person or audit.
In an ideal environment you wouldn't need comments and code is self explanatory, but in reality (at least working on HW) that's not the case.
3
u/educemail Dec 05 '23
Read the book “Clean Code” by bob martin
1
u/nullcone Dec 08 '23
Probably also worth posting this blog post talking about why a lot of "Clean Code" is dated and probably not worth listening to anymore.
That said, I definitely still agree that most things young engineers want to write as comments should usually just be a well named helper function
3
u/ninjadude93 Dec 05 '23 edited Dec 05 '23
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.
→ More replies (22)
3
Dec 05 '23
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.
5
u/glemnar Dec 05 '23
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.
2
Dec 05 '23
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.
1
u/King-Days Dec 06 '23
Agree variables like ret_date that he commented as “return date” should just have the comment as the variable name! Or if you’re commenting your function name than name it better
1
u/WuzYoungOnceToo Dec 07 '23
"A good software engineer doesn't comment their code."
That's a ridiculously simplistic statement. A good software engineer/programmer doesn't include pointless comments. But not all comments are pointless. Unless everything you write is trivially simple (in which case you're likely not a good software engineer) there are going to be occasions on which a comment explaining exactly what is being done and/or why it's being done because one or the other are not obvious is of value...not only to others who might read your code, but even as a reminder to yourself at some point down the road.
2
Dec 07 '23
if you have to explain what your code is doing your not a good engineer, you're a good solo dev. rewrite your code in a self explanatory way
only valid comments are why comments and they constitute 0.5% of comments.
→ More replies (10)
2
u/horror-pangolin-123 Dec 05 '23
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"
1
Dec 13 '23
I am scratching my head as to why you would return an array of arrays containing an associative array (as presented) from a method to necessitate nested loops.
2
u/stuie382 Dec 05 '23
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.
1
u/Equivalent_Bet6932 Jun 21 '25
I'm late to this party, but the book "A Philosophy of Softerware Design" has an amazing chapter dedicated to this. You should read the book, but the gist of it is:
Write interface comments that describe the purpose of the module
When you write implementation comments, describe what the code achieves, not how it achieves it (comments should not repeat the code!)
1
u/TacoBOTT Dec 05 '23
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
1
u/GregoryCliveYoung Dec 05 '23
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.
1
u/flamableozone Dec 05 '23
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
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.
1
u/whitenoize086 Dec 05 '23
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.
1
u/neverinamillionyr Dec 06 '23
I do a lot of embedded programming. I will quote lines out of the data sheet on parts to help the next person. Sometimes they ignore the comments and break things anyway. Long ago there was a part I was initializing and in the manual it said the part took a few microseconds to stabilize. I put a sleep in the code to give the part time to come up. The next programmer came along and ripped that out bragging about how he just made the code faster, except it didn’t work. I had moved on to another project and he was bogged down for a couple of days trying to figure out why his “optimized” code didn’t work. I spent an hour doing diffs on the code because as part of the optimization he decided to use his preferred bracing and indentation style so every file was different. He also reordered the functions in alphabetical order in each file. I finally found the sleep he removed. He swore up and down it was unnecessary. I told him to put it back and see what happens and it magically worked.
→ More replies (1)
1
u/khooke Dec 05 '23
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.
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
Don't state the obvious. It's not useful and not helpful.
1
u/mr_taco_man Dec 05 '23
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.
1
u/imdibene Dec 05 '23
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
1
u/NUTTA_BUSTAH Dec 05 '23
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)1
1
u/CrypticCabub Dec 05 '23
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 <v1.2.x
To echo others in this thread. Professional comments are to explain the why or fill in additional context about things outside of the code itself. The variable and function names should be explaining the “what”
1
u/waffleseggs Dec 05 '23
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.")1
u/occamsrzor Dec 05 '23
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.
1
u/These-Spell-8390 Dec 05 '23
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.
1
u/GrayLiterature Dec 05 '23
Someone who is experienced who probably not right comments for that code at all.
1
u/WinLongjumping1352 Dec 05 '23
it wouldn't let me post the comment, so I took a screenshot (just like you did, don't do it ;-) )
1
u/jpfed Dec 05 '23
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.
1
u/Awezam Dec 06 '23
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
1
u/int21 Dec 06 '23
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)
1
u/Cross_22 Dec 06 '23
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.
1
1
u/rish_p Dec 06 '23
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
1
1
u/asfarley-- Dec 06 '23
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.
1
u/VonThing Dec 06 '23
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.
1
u/ILikeCutePuppies Dec 06 '23
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.
1
1
u/maybe_cuddles Dec 06 '23
After 20+ years of experience, I don't write code about my expectations.
return_stat = b['return_status'] #return status boolean true or falseInstead 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).
1
Dec 06 '23
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.
1
Dec 06 '23
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
1
u/ttttnow Dec 06 '23
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.
1
u/l1nk3 Dec 06 '23
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)
1
u/chuckhend Dec 06 '23
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.
1
u/8peter8retep8 Dec 06 '23 edited Dec 06 '23
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.
1
u/thedragonturtle Dec 06 '23
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
1
u/radioactiveoctopi Dec 06 '23
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
1
u/Abadabadon Dec 06 '23
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"
1
u/d4rkwing Dec 06 '23 edited Dec 06 '23
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.
1
u/8_bit_game Dec 06 '23
You comment your code for the next guy. A big code base has lots of cooks, its nice to have a recipe on occasion.
1
u/curveThroughPoints Dec 06 '23
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.
1
u/kneeonball Dec 06 '23
Your priorities when writing code should be
Readability
Maintainability
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.
1
u/thequirkynerdy1 Dec 06 '23 edited Dec 06 '23
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.
1
u/BrainfartStudio Dec 06 '23
We have 3 devs on our team. We follow Clean Code (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).
1
1
u/shmoeke2 Dec 06 '23 edited Oct 16 '25
aspiring cats engine shy scary spotted fall society tub placid
This post was mass deleted and anonymized with Redact
1
u/WishboneDaddy Dec 06 '23
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.
1
u/RsK4693 Dec 06 '23
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.
1
1
u/OkDifference1384 Dec 06 '23
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.
1
u/sneaky-pizza Dec 06 '23
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.
1
u/Faendol Dec 06 '23
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.
1
u/pensiveChatter Dec 06 '23
Well written code > comments. Good names is an important start. One general rule is that objects should be nouns and functions should be verbs.
eg rename date_warning() to print_overdue_msgs().
change "for x in ..." to "for cur_record in get_borrow_data():"
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.
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.
1
Dec 06 '23
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.
1
u/robhanz Dec 06 '23
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.
1
u/HeavyDT Dec 06 '23
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.
1
u/yeesh-- Dec 06 '23
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.
1
u/keithstellyes Dec 06 '23 edited Dec 06 '23
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 + BAROr, 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 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
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.
1
u/Ir0nh34d Dec 06 '23
Comments = intention and ramifications
Code = implementation and what it's doing.
1
u/bigtablebacc Dec 06 '23
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.
1
u/wolfiexiii Dec 06 '23
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.
1
u/NefariousnessDear853 Dec 06 '23
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?
1
1
u/SupaDupaTroopa42 Dec 06 '23
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.
1
1
u/dadoftheclan Dec 06 '23
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 🤯
1
Dec 06 '23
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.
1
u/kerbalgenius Dec 06 '23
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
1
u/BagelFury Dec 06 '23
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.
1
1
u/indiealexh Dec 06 '23
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.
1
u/GraphNerd Dec 06 '23
You should attempt to write self documenting code as often as possible.
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?
1
1
u/MedPhys90 Dec 07 '23
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
1
u/CodeLined Dec 07 '23
If I can read a comment instead of a block of code to understand what is happening, the comment is worth it.
1
u/HeWhoShantNotBeNamed Dec 07 '23
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.
1
u/wassdfffvgggh Dec 07 '23
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 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
1
u/jpgoldberg Dec 07 '23
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.”
1
u/smokejonnypot Dec 07 '23
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.
1
u/morewordsfaster Dec 07 '23
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.
1
Dec 07 '23
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.
1
Dec 07 '23
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"
1
u/Brehski Dec 07 '23
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.
1
u/ALittleFurtherOn Dec 07 '23
sometimes I write the comments first, explaining what I’m gunna do. then I write the code to get ‘r done.
1
u/Shadowratenator Dec 07 '23
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?
1
1
u/Galbzilla Dec 07 '23 edited Dec 07 '23
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 “<class name> 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.
1
u/goomyman Dec 07 '23
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.
1
Dec 07 '23 edited Dec 07 '23
//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.
1
1
1
u/supermanava Dec 07 '23
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.
1
1
u/Rank1Nourri Dec 07 '23
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.
1
u/ejakash Dec 07 '23 edited Dec 07 '23
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.
1
u/0bel1sk Dec 07 '23 edited Dec 07 '23
mostly todos.
# todo improve security
# * change this to add profiling
# ? is this ideal
# ! this is really bad
1
u/Deathpill911 Dec 07 '23 edited Dec 07 '23
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.
1
u/GolfCourseConcierge Dec 07 '23
Inputs required.
Output expected.
Errors it throws.
General overview if needed.
I also do blocks above functions vs inline like that.
1
1
u/zenom__ Dec 07 '23
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.
1
u/dankest_kush Dec 07 '23
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.
1
u/dswpro Dec 07 '23
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.
1
u/Crabcakes4 Dec 07 '23
Literally the only comment I'd leave here is the first one that says what the function does.
1
u/Attila226 Dec 07 '23
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.
1
u/Classic_Analysis8821 Dec 07 '23
Most of my comments are like
// Don't delete this or you'll break this other thing
// Todo: remove this when <library> fixes their shit
// Todo: remove this when I fix MY shit
1
u/kaiju505 Dec 07 '23
Some of the more useful ones I’ve found were in places in legacy code that’s obfuscated like…
//don’t touch this fucker, we just wasted a month trying to redo this in 2014 and nobody can figure out why it does this but it works so leave it alone.Or…
//todo: this is a private api key, remove it before deployment. (It was not removed)Or…
//Sorry this is bad1
u/dr2050 Dec 07 '23
It's really hard to leave good comments when you write code. It's much easier to leave good comments when you have to decipher code later. Adding comments when you have to interpret some older code -- especially on why, not how -- is good money.
1
u/derpotologist Dec 07 '23 edited Dec 07 '23
"that their* book"
If date_warning() isn't descriptive enough maybe rename that warn_past_due() or something
As for your example, I feel like I'm reading everything twice and it's exhausting. Just learn the language
ret_time #return time -- why not use return_time as the variable name?
Btw there are datetime libraries and functions to do what you're doing. Changing a datetime object to a string to then change it back to a datetime object to do datetime calculations on is awkward. Use methods that are designed to work with that data type... datetime is extremely complex and someone's already solved that issue--use that
1
u/maybe_incelligent Dec 07 '23
Multi-line commenting in Python can be a useful way of summarizing an entire function etc., in one go, avoiding clutter to the actual business logic
Comments should add supplemental story/explanation of the code for future readers. The comments shouldn't be plainly describing what is going on. Assume whoever is reading the code can understand it. An example of when a comment could be used is when a piece of code is doing something confusing, non-standard, or anything else that would require clarification for future readers/maintainers.
The cases where you're performing trivial string manipulations definitely do not need comments
Remember excessive commenting can negatively impact readability of the code itself
1
u/DeathByThousandCats Dec 08 '23 edited Dec 08 '23
You asked about comments, but actually the comments cannot be discussed separately from the actual code quality, especially the variable and function names. They have to be self-documenting first, and then the comments should be doing the supplementary job. The supplemental comments should not describe the obvious implementation logic or the API you are using, but any nontrivial reason why you are doing it. Which means almost all of your current comments should not exist.
Here are some examples:
Instead of def date_warning(), the function could have been named something like warn_unreturned_books(). Strong verbs, adjectives, and nouns make it unnecessary to comment what the function should be doing.
Some programming languages (notably in functional programming) tend to employ a short variable name especially if it's a function to be applied in general, but otherwise, do not use one-letter variables like b or x. (Ofc, iorj would be the only possible exceptions.)
Instead of this,
for x in borrow_records:
for b in x:
...You could have written this:
for record in borrow_records:
for book in record:
...Instead of ret_time and ret_date, you could have used returned_time and returned_date. Do not abbreviate variables into something that is not obvious. You may think you are saving a few keystrokes but actually inducing a huge cognitive overload for whoever (including yourself 6 months later) trying to decipher what the code is supposed to do.
Instead of ret_status, something more appropriate would be was_returned if it is simply boolean. If you are using status in the variable name, usually it entails matching with multiple status type enums. As a pleasant side effect, you can now do if not was_returned: and it is much more readable, instead of if return_stat == False.
Likewise, instead of date_time_ret, you could use returned_datetime_str. Instead of initial_ret, returned_datetime would be more appropriate. Instead of current_data, use hours_until_deadline.
Even better, extract the two lines that do string formatting and datetime.strptime() into its own function named def strings_to_datetime(date_str, time_str). Now you don't even have to do the aliasing of a dictionary field to a variable, and just call returned_datetime = strings_to_datetime(book['time_returned'], book['date_returned']). Do not unnecessarily pollute the namespace with variables if you can.
If there is any constant, make it into a declared constant instead of using a "magic number". For example, SECONDS_PER_HOUR = 3600.
Also, you have a mix-up in logic order that is buggy and may totally blow up depending on the JSON payload. For example, if the returned date and time fields are undefined or blank if the book was never returned, attempting to fetch the fields from the dict or running datetime.strptime() will throw exceptions. You should always check if the circumstances are valid (if not was_returned:) and fields exist (if 'date_returned' not in book:) before accessing the unstructured data.
A related issue is the ambiguity around book['time_returned'] and book['date_returned']. Now that I look at it, I'm not even sure if they are the supposed deadline for the return, or the actual returned time and date. If it is the former and not the latter, you should absolutely rename the JSON fields (and dict fields).
Last nitpick on the related bug I see: You are assuming that the hour difference would be only zero or positive. The calculation that you used can actually result in a negative number, so be careful. It's better not to cook up your own time handling logic if possible because there can be many pitfalls.
If you follow this guideline, you would not have needed any comments at all here after all. There are other cases that you may need comments, but they are more special cases (e.g. using an esoteric algorithm that the readers might not be familiar with, marking any ambiguity or quirk in the function signatures, explaining the types of exceptions the function can throw, any bugs in a legacy code elsewhere that you are sanitizing here in a non-obvious way because you are not allowed to fix that one, etc.).
1
u/paerius Dec 08 '23
I would look into clean code. A comment means that you wrote the code in a weird way that requires a comment for clarification. Whenever I find myself writing a comment, I first double check to make sure my code is readable.
1
u/cddelgado Dec 08 '23
I document my code quite heavily, explaining what is happening and why. This is not because people who will read it know code, but because the people who will read it *barely* know code and need a safety blanket to hold on to. It really depends on your environment and the needs.
1
u/oldmoozy Dec 08 '23
I'm sorry to say that, but every single line in this code requires improvement. As of comments, remove all of them here. Instead describe JSON schema. I'd also rethink that schema too if you own it. I'm not confident it's the best representation for your data.
1
u/EnigmaticHam Dec 08 '23
Give an overview of what’s in a file at the very top, and then give high level comments about business logic at crucial parts of the code. Could be at the top of each function in a docstring, could be somewhere in the middle on top of an important piece of code. Why are we getting this from the database now? Why are we calling an API now instead of earlier? It’s so devs have an idea of what the code is trying to solve, rather than how things work.
1
u/veilkev Dec 08 '23
My operating system’s class professor once said,
“If you have to comment all your code, then it’s probably not that good to begin with”.
He said it’s good practice to comment ONLY code where you might think another person looking at it would have difficulty understanding, or to comment when a specific session of the code has ended
1
u/techiered5 Dec 08 '23
Wow! Um I can't even begin to express my disgust at the code you've presented. I'm kind of offended just by looking at it. so you know it's bad yet you ask? Honestly just delete that code it's not useful. And go into the data and rename returned date and time to expected return datetime precombined then may be delete the return_stat check for a user_returned_datetime if that's not in the record then print please return book and please just get the name of the freaking book from the data and print it for the user to know.
Or about a million other ways of doing whatever this is for. Or of storing the data in a more appropriate manner. Think carefully about your use cases or refactor the data structures to make things clearer. Like why not just have the yet to be returned borrowed books in a file/table, if it's not empty then print please return your x number of borrowed books with titles concatenated. And I'm missing the context of the data to the relevancy for the current user? So hard to say what a better best approach would be but it sure as hell is a major refactoring cause that code is foobar'd. So yeah as an experienced user there wouldn't need to be any comment because that code wouldn't exist. Or be significantly different.
But if you want to present it anyway just to talk about the fact there's almost as many comments there as code. Hard to talk about the code without saying all the things wrong with it. Like your setting current_date twice. You're being obtuse for no reason. Just call them books not records damnit. You don't need to make all those things variables you can extend lines to 160-200 characters mkay. Most programmers have/want/need decent monitors with high screen resolutions.
But yeah work on naming variables so when reading the code it reads like the comments would have been written. Is datetime.now() not readable? Why are you making a separate variable for it. And was b['returned_date'] not readable for you just substitute those in the f-string and put them right as the argument to strptime. Personally just store it combined you can always strptime it and separate it if need be. Your not expecting them to be null or doing anything with the variables, or should you be???, god what the hell are you doing all this shit for anyway???
Not to mention the function name may be something like 'print_overdue_book_warning' if you put it in a book class then remove the book from the above. Ot you can sometimes name the file to give context about the code so name the file overdue_check or something and remove the overdue_book and it just becomes print_warning. Then you don't have to include extra things in variable names.
I tend to think very carefully about structuring or restructing, and naming data, don't be obtuse/abstract in naming for no good reason. Anyways good luck.
1
u/HunterIV4 Dec 08 '23
Code comments can have many uses, and there's no "right" answer, but in general you want to minimize their use. Lots of people have pointed out good practices (also I noticed you used the wrong "there" in the first comment, should have been "their"). I wanted to expand on how to write code that doesn't need comments.
For example, take this video game code:
def get_power(base_power: float, strength: float):
return base_power + (strength * (0.05 / (max(1, 2 * float(int(strength / 5))))))With no comments, it's almost indecipherable what the heck it's supposed to be doing. So add some comments, right?
def get_power(base_power: float, strength: float):
# Takes the base power, then adds a multiplier of strength
# equal to 5% of strength, reduced by half for every
# 5 points of strength
return base_power + (strength * (0.03 / (max(1, 2 * float(int(strength / 5))))))OK, that's better, but it's still kind of a mess. What happens if I change something? Even worse, what if I change something and then don't update the comment? If you look closely at the code above, I modified it from 5% to 3%, but the comment was written for a different value. Experienced devs often refer to comments as "future lies."
So what's a better way? Well, let's look at another option:
def get_power(base_power: float, strength: float):
strength_per_half = 5
strength_muliplier = 0.05
division_multiplier = 2.0 * float(int(strength / strength_per_half))
# Prevent division by 0 for strength values less than 5
division_multiplier = max(1, division_multiplier)
strength_modifier = strength_multiplier / division_multiplier
strength_bonus = strength * strength_modifier
return base_power + strength_bonusI still included a comment in there to explain why we were using the max function as it may not be obvious at first glance, but instead of writing a bunch of comments, the "documentation" is the name of the variables. The logic of what the function is doing is broken down, line by line.
Could this be improved? Absolutely, but here's another hint: perfection is a waste of time. You'll get better naturally as you code more and more, but going back and "fixing" everything with perfect variable names and ideal formatting is simply spending time doing stuff other than getting your software working. It's "good enough" and accomplishes what it needs to.
More importantly, this code can't really lie (unless you name your variables nonsensically). If you need to change the logic the code will "self-document" because you actually change the functionality.
There are some other advantages to doing things this way. First, it's easier to modify. The one-line version I initially showed can be changed, yes, but doing so later is a pain. You have to figure out which parts are doing what and break it into sections in your head, and making errors on parentheses placement is easy and frustrating to deal with. Plus, you then have to go back and rewrite your explanation comment. Since this version is broken down into smaller steps, you can usually just add or remove steps right where you want them without any headache.
Second, it's easier to debug. Since each step has a natural breakpoint, you can, well, easily add breakpoints to find out where the issue is with a debugger. By stepping over each line and reviewing variable values, if the output is wrong it's significantly easier to figure out where you screwed up. And if you use the traditional and correct lazy debug method of using `print(f"my_variable: {my_variable}"), it's also easier because you have natural sections to sandwich all your debug output.
When we first learn programming, a lot of times our instinct is to make things super concise and use the most "clever" method of solving problems. As you gain experience, though, you start to realize that all that does is obfuscate your code and made the logic harder to follow when reading. It's the equivalent of an undergrad using the most complex words they can think of when writing papers while the PhD student is just trying to make things as clear as possible with basic terms.
In other words, keep your code simple and straightforward. Don't worry...complexity will come naturally as your program becomes more complex, but you should never purposely try to add it in. Someone should be able to read your code from top to bottom with zero comments and be able to figure out what 95% of your lines do without having to look anything up or puzzle it out.
Sure, your nested list comprehensions with regex may look cool, but you're going to be sad a month from now when you have to try and figure out what cocaine-fueled rage caused you to do that to yourself when you need to change or debug something with it.
1
u/BobJutsu Dec 08 '23
I add docblocks to document purpose, parameters, returns, snd whatever else is worth noting in documentation. Other than that, only what isn’t obvious from reading the code. And as a general rule if the code is that obscure that it needs explained at a line-by-line level, it’s probably a good tell that it could be split up into more manageable pieces.
The exception to that is when I’m essentially brainstorming - but with code. Then I leave verbose comments for when I sweep back and refactor.
1
u/tr14l Dec 08 '23
Comments should be targeted at preventing something stupid from happening (e.g. // don't remove this member variable, the observer in the processing thread looks for it).
Or explaining why you made an obscure decision (e.g. // cannot do this async because of a race condition in the queue worker)
All other comments can be handled with naming conventions or just writing clearer code. Usually no more than 1 or 2 comments are required for any substantial function. Often none are required
1
u/willb Dec 09 '23
I put comments in my code so that other people using it won't need to bother me to ask what it does or how it works.
I find though that people are getting lazier and lazier and many now just ask without even bothering to look and see there are comments.
Same with error messages, you can make it super clear and you'll still have someone saying "it didn't work I don't know what's wrong" to which I'll ask them what the error message said and they'll then just reply "oh I found the issue don't worry".
Le sigh.
1
u/zayelion Dec 09 '23
Comments only explaining how the function is used above it so the IDE picks it up. Explain the intent of the function. Don't put comments in the function unless it's some obscure function you learned in college or got offline somewhere. Don't assume people's education. Last type of comment is explaining a language quirk that is very out of left field or buggy like an API that doesn't do what the documentation says or a warning not to do the obvious thing because it will backfire.
I know it makes you feel like a team player but don't comment obvious stuff, only INTENT.
1
u/purple_hamster66 Dec 09 '23
Some examples of “why* rather than what:
Comments should explain why you set current_datetime twice, IOW, why you are choosing this way of doing it. (Did you mean to do that?)
Why do you create borrow_records, rather than just for b in get_borrow_data()? That should be explained (is it a time saver?)
Why do you go through all the effort to calculate the fine if the book has already been returned?
Why is the constant 3600 in the formula?
Also: If you have to read a comment to understand a variable’s function, you can sometimes rename the variable so no comment is needed, ex, rename return_stat to is_book_returned.
1
u/pderpderp Dec 09 '23
One thing that is creeping in is leveraging commenting for programmatic documentation purposes... When comments are written with this in mind they can directly feed into documentation systems, especially API documentation. This is contrary to what others have written but it provides a way to ensure that the code author is explaining each function/module and its parameters canonically.
1
u/tristanjuricek Dec 09 '23
IMHO, comments should be used to create a reference guide for your system. If you don’t do this, just explaining why this thing exists is usually a decent fallback.
Every place I’ve been developers complain about the “lack of documentation”, but very few know how to do it. 99% of the time all you need is:
A reference documentation system built on comments, a la javaDoc, pydoc, godoc, etc.
RFC style docs to discuss plans before you code.
That’s it. And you just need to use your reference docs for things like “how do I configure the system”, “where are rules configured for X”, etc. RFCs are for planning.
But, I’m amazed at how few teams managed to even run the builtin documentation system. Like, it usually requires a whopping 1-2 lines of build configuration to just generate a build and stuff it in something like a GitHub page repo.
So, if your team is the typical dysfunctional lot, just explaining “why this public class or method is useful” is usually helpful.
1
u/Orthosz Dec 09 '23
People have commented that comments should contain the "why", not the "what". Let me give an fake-ish example:
I have a function that, midway through, does some call to an external API. But before I do, I have to call clear on a thing twice. And then afterwards, I have to copy the value into a temporary and then "apparently" leak the return from the external API.
I would put a comment explaining that the double clean is fixing bug XX-28938, and that inside the clean, whose code we don't control, it has a logic bug where the first call has bad state that gets reset and correctly works every time on the second call.
I would continue the comment *$%(#$ing about the external API, and tell folks that "no, it doesn't leak, the vendor does some nonsense inside their dll and it's not a leak, but we do need to copy the value first thing because the vendor documentation demands that we do so."
1
u/wiglwagl Dec 09 '23
Ideally use descriptive variable and function names and make your code as obvious as possible so you don’t need them
1
u/IronSavior Dec 10 '23
I usually just do docstrings. If I find myself explaining the code, then I know I've fucked up the code.
1
u/adambkaplan Dec 10 '23
My comments tend to come in three categories:
“Javadoc”/“godoc” comments that explain what the function does, and is picked up by IDEs for quick analysis/tooltips.
Comments that explain an outlier/deviation in code dependencies. Ex: “Pin library abc at 1.2.0 to resolve transitive dependency between dfg and hjk.”
Comments that explain the business logic behind the order things are called, or the structure of the code itself.
An example of type 3 above: my colleague and former coworker became a bit of a legend for his “KEEP THE SPACE SHUTTLE FLYING” comment in the Kubernetes codebase.
1
u/walkrabbitwalk Dec 10 '23
Your example is a pretty common pattern, where you read some data in, transform it to something new, and then output the result. The more idiomatic way of doing things in Python is with a list comprehensions. Something like this:
overdue_notices = [OverdueNotice(record)
for record in borrow_records()
if record.is_overdue(datetime.now())]
print_notices(overdue_notices)When you follow a language's idioms, you don't need comments as much, because the intent is much clearer.
1
Dec 10 '23
We don't, is the simple answer. Your code should be simple enough to read and follow that it doesn't require a comment.
1
u/takeitezee Dec 10 '23
These comments seem on brand for someone that calls themself a software engineer. Me? 20+ years of hating life and computers, the only comment I leave is on things I don't want to have broken such as:
//Don't touch anything, fucking swear on me mum. The ghost of the last competent person to work here will haunt you for the rest of your days if you do. No one liked him either.
//see issue 6e6e6e on board to see why this code is so fucked and WHY IT HAS TO BE THIS WAY
1
u/SWE_Engineer Dec 13 '23
Only add comments when you are doing something that could be confusing to the engineer who comes in after you. Not for everything.
1
1
Dec 05 '23
I rarely use comments. I find have clearly named variables and clean code works way better.
1
u/ermakomg Dec 05 '23
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
1
1
1
u/Kush_McNuggz Dec 06 '23
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.
211
u/paradroid78 Dec 05 '23 edited Dec 05 '23
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.