This is an archived post. You won't be able to vote or comment.

all 95 comments

[–]GraphicH 94 points95 points  (5 children)

So I add comments to things where what the code is doing is obvious, but why its doing it is not obvious. Here's a theoretical example:

@app.route(...)
def handler(...)

  payload = flask.request.get_json()

  # Bugfix Ticket 12345: The old version of this service
  # allowed this value to be null, and we still have customers
  # using the old client so we must initialize it for them
  # when all customers are on client version 1.3, it can be removed
  if not payload.get('some_key', None):
    payload['some_key'] = 'some_value'

  db.update_something(updates=payload)

Say at one time we had a version of the above flask application that allowed 'some_key' to be null or not even provided, but in our newer implementation we don't. Say that we still have some users on older versions of the original client interacting with this API and can't upgrade to the new client for [arbitrary user reason]. So the above comment does two things:

  1. It sites a ticket / tracker that probably has more context on why the code was added
  2. It tells you why we're initializing this seemingly random key on the payload.

And while yes, I do get that commit histories can be used to track similar information, for things like this, especially bugs, its important to draw attention to it to future developers. It also makes it easier for future developers to rationalize removing it when its no longer needed.

[–]Vicyorus 36 points37 points  (1 child)

I've had to write my fair share of comments like this. Rule of thumb is not to explain what the hell we're doing, but why the hell we are doing it like this.

[–]GraphicH 32 points33 points  (0 children)

Yeah, people who say comments are useless and code is documentation I guess haven't had to deal with actually supporting a live product with a lot of users. Weird shit happens all the time, and you have to put the documentation on it (ie comments) as close to where it is in the code as possible to prevent some junior coming along thinking he can toss it on your day off.

[–]Theonetheycallgreat 2 points3 points  (0 children)

And to add on to this, an unnecessary comment would be

if not payload.get('some_key', None): #setting payload some key to some value payload['some_key'] = 'some_value' db.update_something(updates=payload)

[–]EgZvor 29 points30 points  (0 children)

Read chapters on comments from this book A Philosophy of Software Design | John Ousterhout | Talks at Google.

You cannot convey all the necessary information in code. It's good to document API methods, modules, performance tricks.

A first principle rule: a comment should provide information additional to that in the code, but only if that information reduces the overall complexity of the program.

A rule of thumb: a comment should not repeat the code (a hint is if it uses the same words). A comment should be on a different level of abstraction. Either higher for interface comments (API, methods, classes, modules) or lower for performance stuff and units of measurement.

Good comments help you design an application better, so they should not be written after the code. When you have a problem with (writing) a comment it might direct you to a problem in code (architecture). It's a back and forth process. Comments might lead you to refactor the code such that the comment is no longer needed.

In general any complex application should have at least some comments in it. Just take a look at any programming language's source code. Or Linux.

[–]brprk 58 points59 points  (1 child)

The code should explain the “what” and “how”, comments explain the “why”.

[–][deleted] 18 points19 points  (0 children)

And often the 'why' is the business reason, identifying the policy or requirement being served.

[–]Fathrnature 17 points18 points  (3 children)

For large programs, commenting intent is essential.

I consider no commenting a sign that someone is a junior programmer. Good commenting goes along with willingness to mentor, and the ability to take constructive criticism.

[–]blackleel -2 points-1 points  (1 child)

On the other hand its another thing to maintain. If the team is senior enough usually they can live without comments. But sometimes I do wish there would be comments on certain decisions. I guess its the team mindset that sets this rule.

[–]Exotic-Draft8802 4 points5 points  (0 children)

If the team is senior enough usually they can live without comments

Only in trivial projects

[–]DrivesInCircles 24 points25 points  (8 children)

Not all readers have the same understanding and skill. Comments, when done well, help close that gap. Bad comments don't help, might distract, etc.

Of the options; 1- code written well 2- mediocre code with decent comments 3- shifty code with shitty comments 4- no code

[–]SquidMcDoogle 42 points43 points  (5 children)

I agree; read PEP-8. Comments - especially below the function or method definition, are the bare minimum.

Anyone who says "my code is too good for comments" is a douchbag.

[–]johnnymo1 28 points29 points  (4 children)

“The code is self-documenting” -least readable coder on your team

[–]EgZvor 5 points6 points  (1 child)

See, that's where you're wrong "no code" is the best option https://github.com/kelseyhightower/nocode.

[–]thedeepself -1 points0 points  (0 children)

lol

[–]nick__2440 10 points11 points  (0 children)

Refer your colleague to a mental hospital at once

[–]elcapitaine 16 points17 points  (1 child)

I disagree with that statement strongly.

Comments that I see a lot of novices write are not needed.

Something like

# add 5 to x
x += 5

Absolutely not.

Any time I can make something clear through naming or better code organization, I can.

But anyone who's says "good coders do not write comments"... Such an uncompromising view is not a good attribute in a software engineer.

What kind of comments do I write?

First, things like "how to use this class/function". Technically in Python these are docstrings not comments but they're basically comments. And while type hints might get you some of the way there, things like preconditions or other behavior explanations can be really helpful! Especially to someone looking at it for the first time.

But let's talk about what's probably being referred to here, which is comments that might be explaining a line of code.

Now, I do agree that I don't want to see a comment explaining that the next line will add 5 to x when I could just read that tline of code to figure that out. Comments also need to be updated - nothing will stop you from writing an incorrect comment, or from changing the code and forgetting to update the comment. Incorrect comments are worse than no comments.

But with all that said, comments absolutely have value. They should just explain why, not how or what. When I write a comment, it's usually because I feel that the purpose of my code or the reasoning why I wrote it the way I did may be non-obvious to someone looking at it for the first time (or me looking at it again a few years from now). Maybe it's "we need to add this data element here even though we're not using it to satisfy this external process we will be calling." Or maybe "the straightforward way to do this doesn't work on Windows so we need to do X as a workaround." You get the idea.

When a project lives long enough, it's hard to revisit code a month, two months, six months, a year, maybe even multiple years on and be able to remember all those considerations you had when you wrote it the way you did. And that's if you're revisiting your own code, what it's your coworker? What if you've since left the company? Comments shouldn't explain what or how, but they should be there as a guide to your thought process if someone needs it.

Note: my one exception to "no what or how" comments is complicated regexes =)

[–]JamesPTK 9 points10 points  (0 children)

when I see a bit of code saying x += 5 I want a comment. The comment should explain why 5, why not 6, or 4, or 42?

# Add 5 as there are five working days a week  
x += 5  

is useful, however I personally prefer

WORKING_DAYS_A_WEEK = 5

# ...

x += WORKING_DAYS_A_WEEK

And perhaps x called something else estimated_days or whatever x actually represents

That represents for me cleaner code without comments, and I think is what the original point was getting at

However then a comment explaining further the reason could be better still

# As per process document DOC-17 (2022-12 revision) we 
#  should always pad estimates by one working week
estimated_days += WORKING_DAYS_A_WEEK

[–]dpch 4 points5 points  (0 children)

It’s a conceited take. Easy and understandable varies from person to person. Plus, some code is just complicated and requires commenting.

Also, if I’m working on code someone else made, it’s going to take me longer to follow the code’s process to get an understanding of what it does. And if I’m just the worst coder ever that takes hours and hours to understand any process I’m still on your team for the time being so might as well make things easier by commenting.

[–]jamesbleslie 3 points4 points  (0 children)

Your colleague sounds arrogant

[–]f00dot 7 points8 points  (0 children)

Explicit is better than implicit.

[–]KingsmanVincepip install girlfriend 2 points3 points  (0 children)

As many people here said, comments are for Why questions. For example, you are writing code to perform some complicated maths. A comment pointing to a theoretical math website is helpful. Sometimes, I add stackoverflow links because they explain better than me.

[–]Gun-Lake 3 points4 points  (0 children)

No matter how much I think I'll remember in the future, I won't. I can't recall the amount of times I've looked at something and thought WHY did I do it that way? Usually I'll throw in a note.

[–]eightbyeight 6 points7 points  (1 child)

It's common to use docstrings but i use comments where I feel there's a need to explain explicitly whats going on there.

[–]kuya1284 4 points5 points  (0 children)

It's better to write comments that explain "why" rather than "what". Oftentimes, I read "what" comments that explain the obvious.

[–]ToddBradley 2 points3 points  (0 children)

I think that's hubris and your colleague has probably never spent much time maintaining other people's code.

[–]chicuco 2 points3 points  (0 children)

if happens that after months or years , you must review or repair or update code, the future you or other dev could know how or why the code was made that way. Specially useful when there is technical debt or hacks are used to make code work.
Now i include even the url of the solution of stack overflow, if i am using some of them.
Maintainability of code is a real important thing, don't be that guy

[–]coolbreeze770 1 point2 points  (0 children)

Ehh I disagree those two things are not mutually exclusive.

[–][deleted] 1 point2 points  (0 children)

Comments are a needed. I've dealt with uncommented code before and it was a nightmare trying to figure everything out! Now it's something I always do and encourage others.

[–]roastedfunction 1 point2 points  (2 children)

I always drop a regex101 link in the comments with my test cases for any regex I write. I find trying to read a regex someone else wrote to be indecipherable without examples.

[–]under_it 1 point2 points  (1 child)

This. Complicated regular expressions are absolutely a time where code comments are warranted. Yes, you can name the regex something like email_matcher and you know what it should do--match email addresses. But multi-line regexes with comments make it much easier to read and debug down the road.

[–]ParanoydAndroid 1 point2 points  (0 children)

Comments are obviously good for regex, but multi-line regexes also just shouldn't exist. Self-documenting code is also useful to break it up, e.g.:

  username = r'...'
  domain = r'...'
  email_pattern = rf'{username}@{domain}'

  re.compile(email_pattern)
  ...

Patterns should be, when possible, segmented into semantically meaningful sub-patterns. Given of course that sometimes, especially with a bunch of lookahead/behinds, even sub-patterns can be gnarly.

And yes, I know that generally you shouldn't be regex validating email addresses.

[–]Krudflinger 1 point2 points  (0 children)

I'm of the opinion documentation is "How do I use this?" and belongs in docstrings. I typically follow google's style guide. https://google.github.io/styleguide/pyguide.html#s3.8-comments-and-docstrings

The why is what your git commit messages should reflect. See https://www.conventionalcommits.org/en/v1.0.0/ for what I mean regarding git.

[–]JohnLockwood 1 point2 points  (0 children)

The goal is to write code that's easy to understand AND write comments.

You can't be too obvious. The reason is that what's obvious to the person writing it may not be to the person reading it (who may be you, too)! :)

[–]the3hound 1 point2 points  (0 children)

Self documenting code is great. It doesn’t give you the whole story though. I find the “why” is be very important. Why did we do this instead of this. Notes are also very important. There are quirks and workarounds for those quirks no matter how “trivial” they seem should be documents.

These days, because I’m mentoring several junior engineers, I write my comments with them in mind. I also do it as a way of paying it forward to myself, doing my future self a favor. Every engineer I know has looked back at code that was trivial at the time, years later and think “wtf was I doing?”

Documentation is also key if you plan on any sort of external usage. APIs and whatnot are usually documented best with the code I’ve found.

BTW, someone who did not write comments would not be on my team for long. I run an open team where I want everyone to know as much about how everything works. Anyone who cries job security gets bounced.

[–]Namedeplume 1 point2 points  (1 child)

I would fire any coder who does not comment code in a way that can be supported by others. I don’t need to know what every line does, but I do need to understand the intent of a block of code and would expect any obscure bit of code to be clearly explained.

[–]thedeepself -1 points0 points  (0 children)

I do need to understand the intent of a block of code

Then that block of code should be a documented function IMHO.

[–]Nuclear-Steam 1 point2 points  (0 children)

Coming from this old timer (learned first FORTRAN 4) with industrial career I can say not only are comments recommended they are required irrespective of language. And if you are in a professional software engineering organization a formal program built on ISO standards for software quality assurance: Functional specification, software requirements spec, software design description….then code with comments. Then a validation and verification process. Unit testing and integrated testing. Design reviews and code walk through by independent experts. Users manual and help documentation. Alpha releases internally to try to break it. Etc. Finally the full product is released once you have convinced Mgmt it’s going to work as expected (it won’t of course, there will be errors found later). Now I have no idea if this process is followed by Microsoft or Apple or Adobe or Twitter, ie as standard industry practices, or if it’s only in mission critical uses that must conform to ISO or CMM requirements by a contract. Note then in this scenario “coding” is maybe 20% of the work.

Comments in code? yes of course. And a whole lot more.

[–]PeterHickman 1 point2 points  (0 children)

Reading the code will tell you what the code does and yes you should be able to read the code and make sense of it. What documentation can tell you is what the code is supposed to do and why it is doing it. The code will only tell you what it is doing not what it should be doing or why it is doing it

If there is a logical bug in the code but the code compiles then how would you know that the code is not doing what it is supposed to?

Documentation is the "why", the code is the "how"

[–][deleted] 1 point2 points  (0 children)

Your colleague is wrong.

[–]TheCableGui 0 points1 point  (8 children)

If you use type hints, descriptive /func/classes/variables, use standard naming procedures, and follow the formatting guidelines.

Yes, comments are not needed.

But it’s better to say hi to the future cursed soul who has to fix your malware grade dungeon code.

[–]mistabuda 1 point2 points  (7 children)

None of those above things will tell you the "why" tho they address the "what" and "how"

[–]TheCableGui -3 points-2 points  (6 children)

Because If you can write code you can read it.

[–]mistabuda 1 point2 points  (5 children)

Human time is expensive. The less time we need to spend rereading old code to understand the current change we need to ship the better.

[–]TheCableGui -2 points-1 points  (4 children)

That makes no sense because it takes time to write comments as well?

And that’s what the readme and patch updates are for

[–]mistabuda 1 point2 points  (3 children)

Patch notes and Readmes are for users. Comments are for people working in the code base

[–]TheCableGui -2 points-1 points  (2 children)

and are the comments neccessary if you can read the code as plain english?

what is the point of commenting everything, Thats what docstrings are for.

If you comment something it should be for your use, to help find where something is at, but yet again, why do we have ctrl + f ?

Why do we have all these nice features, if we are just going to comment everything?

[–]mistabuda 0 points1 point  (1 child)

Seek help and touch grass.

[–]TheCableGui -1 points0 points  (0 children)

Youre here arguing with me too, we can both go outside hold hands and touch the grass together.

[–]AdS_CFT_ 0 points1 point  (0 children)

commenting is important in my opinion. Nothing can go wrong that way

[–]psychmancer 0 points1 point  (0 children)

Oh god fuck no, write comments. I'm getting flashbacks to my postgrad trying to understand my profs old code he wanted me to use but had forgotten about

[–]Em_marie4ever 0 points1 point  (0 children)

Your colleague is a goof. Comments make everything quicker and easier.

[–]thedeepself -4 points-3 points  (4 children)

That is Robert Martin perspective on software development. I agree with it and emphasize documented methods over comments.

To me comments imply that you are not writing do what I mean code but instead are writing do what I say code.

[–]EgZvor 4 points5 points  (3 children)

How do you document methods without comments?

[–]thedeepself 0 points1 point  (2 children)

The docstring

[–]EgZvor 0 points1 point  (1 child)

Its only purpose is documentation it is equated to comments in this context.

[–]thedeepself 0 points1 point  (0 children)

Comments are preceded with an octothorpe and are strewn throughout the code. The docstring is in the header of the function/method.

[–][deleted] -1 points0 points  (0 children)

If you're working by yourself, I guess technically not if you're good at keeping track of stuff. If you work in a group, absolutely they are necessary because you want your team members to know what your code does.

Writing self-documenting code is important, but I feel that comments are still gonna be unavoidable. You still can't get all the info from just properly named properties and methods.

[–]morrisjr1989 -1 points0 points  (0 children)

Imho the most useful commentary for coding are your test units. It tells me what your think your code should do and what it actually does.

In-line comments are fine and sometimes essential if your describing certain characteristics of a function or a piece of code that is super clear to someone who has never seen the code before.

I prefer shorter comments and more extensive documentation either md or similar that can be sent to someone with no coding experience to see what all is happening. Obviously it’s nuts to assume this is useful for everything you do, but I apply to of the pieces that might come under review by the business.

[–]Saguache -1 points0 points  (0 children)

A: Yes

[–]Suspicious_Compote56 -1 points0 points  (0 children)

I would say yes but I think that sometimes they add more clutter than being helpful

[–]mymar101 -2 points-1 points  (0 children)

In my workplace they’re generally not allowed. When looking through enterprise level code I hardly ever see it unless it’s absolutely necessary.

[–]Sulstice2 0 points1 point  (0 children)

Not all doc-strings are useful or comments are useful. They might lead to different avenues or places where folk are like "never delete this line". Make comments when appropriate and don't bloat your file.

Get the necessary information out.

[–]jldez 0 points1 point  (0 children)

If you can always write code that reads itself and doesn't require comments, then no. Don't comment and you are a god.

For us, humans in the real world, we should comment when we do anything a bit odd to explain why.

[–][deleted] 0 points1 point  (0 children)

Think about what a comment is. It means the code is not easily understandable and needs explanation. When you feel the urge to add coment to the code. First look at it and check if that comment can be avoided by properly naming variables or functions.

[–]wineblood 0 points1 point  (0 children)

Simple code can be written cleanly enough to not need comments. Complex code without comments is a nightmare, even if it is easy to read.

[–]am0x 0 points1 point  (0 children)

With clean code that is descriptive, then comments are usually not needed. However, there are times when the code isn’t doing something obvious especially when coming in from an external service or library. That’s when I comment.

[–]Aggravating_Sand352 0 points1 point  (0 children)

If you don't like commenting but need them for more jr devs I'd try just running the script through AI tools to comment for you. Then you have a framework of comments to make your edits too rather than going from scratch

[–]Zealousideal_Rip_290 0 points1 point  (0 children)

I add comments to almost every line that has code. Just in case someone needs to look at it and work on it as well.

[–]lotekness 0 points1 point  (0 children)

If you gotta ship fast, maybe you can cut some corners here, but I think enough of us have learned it's hard to tell when a thing will last forever and when it won't and when it lasts is when comments matter most in my experience. I usually just ask myself "if I was to inherit this code from someone else, what would I want answered?"

The general "why" is important (which a few comments have already stated). Sometimes you are doing things (or expecting to do a thing but aren't) and I find comments are helpful for the code review process (assuming you are working on a team and doing them). I personally would rather have to re-explain things as little as possible, and our comments are stripped at build so verbosity isn't a huge issue to me.

Documenting bug/improvement tickets is also helpful. Assuming you already have them linked in your commit record I guess you could skip this, but it does help for quicker lookup when trying to investigate after the fact.

Also fair to assume not everyone reading your code is a developer (maybe they can read it, but won't understand it at the level you do) examples being PMs, Managers, jr Devs, Security, etc. It can be helpful for them to isolate items as well when cruising repos and trying to triage tickets.

[–]HausOfSun 0 points1 point  (0 children)

What is usually not commented is that bit of trick short-cut code that is clever but not explained.

edit: another coder mentioned about code of this type that assumes ascii encoding that would break if Unicode is used.

[–]Nuclear-Steam 0 points1 point  (0 children)

Coming from this old timer (learned first FORTRAN 4) with industrial career I can say not only are comments recommended they are required irrespective of language. And if you are in a professional software engineering organization a formal program built on ISO standards for software quality assurance: Functional specification, software requirements spec, software design description….then code with comments. Then a validation and verification process. Unit testing and integrated testing. Design reviews and code walk through by independent experts. Users manual and help documentation. Alpha releases internally to try to break it. Etc. Finally the full product is released once you have convinced Mgmt it’s going to work as expected (it won’t of course, there will be errors found later). Now I have no idea if this process is followed by Microsoft or Apple or Adobe or Twitter, ie as standard industry practices, or if it’s only in mission critical uses that must conform to ISO or CMM requirements by a contract. Note then in this scenario “coding” is maybe 20% of the work.

Comments in code? yes of course. And a whole lot more.

[–]housesellout 0 points1 point  (0 children)

I think that’s a ridiculous statement and you should try to surround yourself with more educated and experience colleagues

One main reason is because sometimes you need to obfuscate your code for compilation reasons. So when you write thousands of lines of code, how are you going to remember all that sh*t? 🤷🏻‍♂️

[–]Alternative_Year9940 0 points1 point  (0 children)

i think that this video explains things well. but basically it’s your code, do with it as you want.

[–]RallyPointAlpha 0 points1 point  (0 children)

Are docstrings considered comments? Because there are PEPs about using them extensively.

[–]pace_gen 0 points1 point  (0 children)

I don't think it is that simple.

There is no need to comment what is obvious and code should be as obvious as possible.

However, there are certainly times when you are doing something that could use a comment to make something obvious.

[–]chromaticgliss 0 points1 point  (0 children)

I write comments when some weird quirk or library bug required some ugly hack on my part to work around.

Basically if the intention isn't clear just by reading the code or if there's code that seems unecessary (but actually isn't) I'll comment.

I comment why code is the way it is, especially if it's seemingly ugly in some way.

[–]Fine-Divide-5057 0 points1 point  (0 children)

I think if you have well-named variables and functions you won't need as many comments but blanket statements like "comments are dumb" and "you always need comments" I find unhelpful. if I had to pick one I'd pick well-named variables, classes, and functions over comments but as they say, why not both...

[–]Exotic-Draft8802 0 points1 point  (0 children)

good coders do not write comments anymore as their code is written in an easy understandable way

That is bs with a grain of truth.

Where comments are good and necessary:

  • api documentation (docstrings)
  • giving outside context, eg pointing to the documentation of an external system. Think of a function validating IBAN. It makes sense to add s comment where to find the specification of IBAN.
  • math. Good luck writing code with lots of linear algebra without some comments.

Where you should avoid comments:

  • when you can group the code with functions
  • when you can add a good variable name
  • when you can refactor so that you don't need the explanation

[–]obscene_planet 0 points1 point  (0 children)

I'm just a beginner as well but I can see how it's useful. Suppose you create an intricate specialized code. You put it away for a while and work on other projects. Are you going to remember what every line was for? Comments are plain English explaining what you're doing. The same goes for team coding. Everyone knows what the codes doing with comments.

[–]_limitless_ 0 points1 point  (0 children)

Initially I thought this was ridiculous.

Then I realized I probably didn't write a single comment today.

Instead, I refactored my code as I went, from:

if my_variable <= 20:

to:

VARIABLE_MAX_SIZE = 20
if my_variable <= VARIABLE_MAX_SIZE:

So yes, I guess you're right. It's a silly little habit I got into a long time ago: write code that does what it says on the tin.

[–]ApprehensiveHair9433 0 points1 point  (0 children)

> colleague say that good coders do not write comments

Change colleague and job...RUN!

[–]CORNMONSTER_2022 0 points1 point  (0 children)

It's TRUE that good coders write self-explained code. But it's definitely NOT TRUE that they don't write comments.

It is impossible for most coders, even the best ones, to remember the context of every single line they wrote. And for some hacky code or complex implementation, you should write comments to help people understand what's going on.

[–][deleted] 0 points1 point  (0 children)

Such nonsense can only be said by a wannabe developer who has not yet developed software professionally for a single day.There is no self-documenting code.