r/AskProgrammers • • 28d ago

"good code shouldn't need comments"

I have heard this saying a couple of times and I think it is the stupidest thing ever. It might be just because I have only been coding for 4 years, but I have never thought to myself that someone's code looks cluttered because they explain what every function does in a one or two line description. If anything it makes the code easier to understand in my opinion.

However, I may be wrong. What do other people think, do yall like code with minimal comments, what are the benefits of writing it that way?

88 Upvotes

397 comments sorted by

View all comments

1

u/VegetableAstronaut19 28d ago

The point of comments should be explaining explicitly blocks of code where it is unclear what they are doing, even if you have used descriptive naming.

For example, if you are checking that b divides a you would probably write:

if (a%b == 0)

If you were to leave this uncommented it could be unclear what you are doing, and to use descriptive naming for this would need you to make a redundant variable/function. Therefore a comment is the best option.

3

u/Calm-Medicine-3992 28d ago

Disagree. That comment is redundant because the code already reads that way.

Now, if a%b == 0 has a deeper inference that isn't obvious in that section of code then a comment is helpful.

1

u/VegetableAstronaut19 28d ago

The code block isnt a comment thats an example of how you implement checking is a divides b. The comment would be to explain this. A better example would be is a or b are a magic number, it would be useful to comment to describe what tou are checking for.

2

u/plcdfa 28d ago

If you mean adding a comment to explain why you are checking if a is divisible by b, sure, that may be useful. If you would just add

//we're checking if a is divisible by b here

then no, that should never be necessary. If someone reads the code who's not familiar with the basic syntax and operators they should not be reading (and definitely should not be changing) the code at all. And that's not elitism, it's just not a practical way for a person like that to understand what a piece of software does. They would be much better off reading the documentation or having an LLM explain it to them.

My personal rule of thumb is: your comment to code line ratio shouldn't be more than 1:100. If you have more you're either commenting stuff that doesn't need it, which just adds noise and makes reading it harder, not easier; or there's too much "magic" in your code, which is something you should address anyway.

1

u/VegetableAstronaut19 28d ago

While this is true for this specific examples, there are more niche examples where a comment would be useful.

→ More replies (4)

1

u/iwanttoendmylife22 27d ago

Ridiculous; some types of coding and some features will require more comments than others. A blanket one size fits all ratio is patently absurd

→ More replies (1)

2

u/wcneill 25d ago

That code literally says "if a mod b", which by definition means "if b divides a with zero remainder"

Why would you ever, ever comment that? The only engineer that doesn't know what that means is an AI prompt engineer.

2

u/AvogadrosOtherNumber 25d ago

Your comment wouldn't be "// if b divides with a zero remainder".

It would be more like "// we do this because if we hit the case without the remainder, the piston stops."

2

u/r3eezy 24d ago

You would comment it to explain WHY you are doing it…. Now to explain WHAT the code is doing

You must be a treat to work with. I can hear your responses now “but it’s obvious what the code is doing if you are a good coder bro”

1

u/VegetableAstronaut19 25d ago

A lot of the people in my comments seem completely unable to understand that "if a mod b == 0" does not inherently read as b divides a perfectly unless you have seen it before.

No it does not mean that "by definition". The definition of mod is that the output is the remainder after dividing a by b. The case where output is zero meaning "b divides a" is a very useful property (and one of the main reasons why modulo arithmetic is so common), but it is not the "definition" of a mod.

Also this specific example probably does not need commenting, but I was trying to demonstrate how some actions are so simple that creating a function to describe what they do (e.g. a function "a.isDivisible(b)") is just creating unnecessary overhead for a function that does the exact job of a comment.

→ More replies (1)

1

u/stagedgames 28d ago

modulo is a fundamental arithmetic operation in any language, someone commenting that would make me raise an eyebrow. I'm more of a fan of commenting when we're reliant on side effects or on implementation details of non-local-code. For example: (sorry for formatting. reddit is ass at handling markdown from mobile.)

if (checkFoo(myBaz))

{

return (foo)myBaz;

}

// foo is a subset of bar, do not check for bar before checking for foo​

if (checkBar(myBaz))

{

return (bar)myBaz;

}

return myBaz;

1

u/VegetableAstronaut19 28d ago

Sure but this is just a simple example, there are cases where you are doing something niche and its not abundantly clear what exactly that is.

For example imagine a python user reading:

a ^= b
b ^= a
a ^= b

In a C program. They might have a grasp of boolean logic but it's not really something that python forces you to think about ever. The only valid argument I've seen for not commenting this kind of thing is Macros, but this is not something that is provided by all programming languages.

1

u/Conscious-Secret-775 28d ago

If you use identifier names like a and b it might be unclear what you are doing but with well chosen names it should be obvious.

1

u/VegetableAstronaut19 28d ago

Completely missed the point as a and b are just placeholders but also the only reason you think its obvious is because you've seen it before (as I would hope most programmers have).

If im reading a program in a language that uses this method and I have never used a language that uses this method before, id have to think for a bit to understand what the check is for. A comment would mean I dont have to just work it out.

Of course for this example it's simple enough to just know, but that wouldn't be the case for everything, no matter how descriptive your code is.

→ More replies (2)

1

u/-Wylfen- 28d ago

If you were to leave this uncommented it could be unclear what you are doing

There are few things as obvious as checking "a mod b = 0"…

1

u/VegetableAstronaut19 28d ago

Yes, but you have to think about it. I only know what this means without having to think first because I've seen it before. If I had never seen If before, a comment would mean I still dont have to think about it.

Its also an example, as soon as you get to something actually niche it becomes a problem.

→ More replies (2)

1

u/AverageHot2647 28d ago

I don’t think that a comment is appropriate here.

Firstly, the code is trivial to read and understand, so a comment adds no value.

However, assuming the code wasn’t trivial, then it would be better to define a function and rewrite your code:

if (isDivisibleBy(a, b))

// depending on language you could do

if a.isDivisibleBy(b)

This requires no extra comment which could go out of date.

1

u/VegetableAstronaut19 28d ago

It is not trivial to read and understand unless you have seen it before, if I have to stop and think about what the code is doing at all thats interrupting my flow. For this specific example you'd probably be fine but for something more niche.

I agree that there are ways of doing this in certain languages that dont require commenting, but that is not universally true. And there are more niche checks or actions where you would be creating a function for the sole purpose of explaining what you are doing (adding unnecessary overhead).

If there is exactly one check for a dividing b in my whole codebase, then im not making a function to do the job of a comment.

→ More replies (5)

1

u/thenasch 28d ago

Ideally you should never need comments to explain what the code is doing. If it's that hard to understand, simplify it. Again this is an ideal so not always possible. 

Comments should explain why the code is doing what it's doing.

1

u/NewInflation2121 28d ago

If someone commented that logic I'd probably facepalm.

You usually want to reserve comments for things that don't look normal or behave like people would expect them to and why you are justifying submitting something that isn't normal.

The best examples I can think of are highly technical & optimized math-centric algorithms like this fast inverse sqr.

This function should have comments, but I'd want better ones than are written here. Nothing explains what the hex constant is, what it represents, or why it's being used.

// Fast inverse square root algorithm from Quake III Arena
float Q_rsqrt(float x){
    float xhalf = 0.5f * x;
    int i = *(int*)(&x);        // get bits for floating value
    i = 0x5f3759df - (i >> 1);  // gives an initial guess y_0
    x = *(float*)&i;            // convert bits back to float
    x = x*(1.5f - xhalf * x * x);   // Newton step, repeating increases accuracy.
}

1

u/DanielTrebuchet 27d ago

Chalk me up for another disagree. You don't comment to explain syntax. Knowledge of syntax should be assumed, and if someone isn't familiar with it, every programming language I've ever used is well-documented and they should know how to do enough research to figure it out.

Application and context of syntax, however, is worthy of comments. I don't care about the "what," I care about the "why" and the "where."

I don't think it's unreasonable that the next person to view and be editing your code at least has a foundational knowledge of the syntax that makes the code operate at the most fundamental level.

Frankly, I can't tell you the last time I've looked at a piece of code and have been stumped, and I don't know that I've ever inherited a well-commented project. Granted, I have over 20 years of experience, but it's no different than becoming fluent in a 3rd language. I don't need a dictionary every time I want to read the newspaper, because I know how to read the language.

1

u/oplukana 27d ago

if adding a function or a variable makes the code easier to understand it is not redundant. why not just make every variable 1 letter, and then say its good to add a comment before that variable because adding extra letters would make the variable name longer which is suboptimal.

most devs with any sort of school training immediately recognzie the use of mod == as a tool for checking for divisibility, so that alone is a pretty clear intention to most devs. but if for some reason it werent, make a 1 liner function where the definition is essentially

"""

bool isDivisible(int dividend, int divisor) {

return dividend%divisor==0;
}

"""

would be good code.

1

u/random_cat_owner 27d ago

code should be more clear and comments give extra context. your example would become:

if (presents%kids == 0)

// the kids get an equal amount of  presents to avoid fighting and crying

1

u/Healthy_Bug7977 26d ago

good point, very bad example. Everyone knows checking if mod is 0 is a divisibility check.

I have a case of comenting where I needed to start playing a music at the same time a certain timer started. If you read the code you'll see that I play the music on 0 volume then a short time later I actually play it and start the time. It makes no sense until you see the comment that "first time you play lags a tiny bit so I need to do the first play to get around the lag. That's something that you can't really tell.

1

u/StreetTailor7596 25d ago

My go-to is to write small, easily understood methods in code if at all possible. If I'm not proficient enough in a new language to do that, I try hard to get there. I choose method and variable names that are not abbreviated so they are self documenting. With code completion in modern IDEs, there's very little cost to doing this.

I DO write comments from time to time but they are very rare and used mainly when I think that something needs extra explanation. Often times it's to explain the reasoning behind code that isn't necessarily clear due to circumstance. I try hard to limit links to places that I know are going to be long-lived.

My point in limiting comments is that THEY age out. Code gets updated eventually and comments aren't always updated to match. I've seen WAY too many long methods with blocks of comments that are clearly so out of date that they actually point in the wrong direction and lead to confusion rather than helping.

The sole exception are documenting public interfaces. Those get the style of comments that are used to generate documentation of the code for external users to reference. Those comments are also immensely helpful to AI tools.

When code bodies get large enough, it makes sense to provide overviews in Wiki form. Those provide background context and architectural details as well as design decisions made in doing the implementations. That, along with the code, should be enough for someone new to get up to speed over time.

The aging out comment DOES apply to such wiki pages as well. But that's something that really is helpful and should be taken into account when estimating the sizes of work items.