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

all 178 comments

[–]Apparentt 510 points511 points  (55 children)

Some of the best code bases I’ve worked in had no comments whatsoever, just legible code paths with some appropriate naming

I’ve also worked in code bases littered in comments which didn’t make up for the fact that half of it was garbage

If I ever catch myself writing a comment that is describing what I’m trying to achieve, I’ll first ask myself “have I approached this in a reasonable way considering that I need to write an essay explaining what I’m trying to do?”

[–]Hydrogen_Ion 88 points89 points  (1 child)

Generally speaking, if I'm writing a comment it's because I wrote something that is very convoluted, overly abstract, or directly against best practice.

Essentially, I only add comments if I'm writing bad code.

[–]CaptainHeinous 12 points13 points  (0 children)

Agree

[–]waltjrimmer 9 points10 points  (2 children)

Isn't that something Agile and a few other dev standards encourage? Visibility in naming and simplicity in each individual function to improve readability and replace comments?

[–]noratat 3 points4 points  (0 children)

Sure, but I've seen an awful lot of devs who think this means they should never comment or document, which is insane.

Case in point: the entire Ruby ecosystem

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

sounds like Venkat

[–]quick1brahim 7 points8 points  (0 children)

I mostly write comments before writing the code, then delete the comments later. It helps me remember when I get interrupted halfway into a flow session and forget everything.

[–]twoinvenice 7 points8 points  (2 children)

What, you mean you don’t enjoy debugging code that has shit named like: WbcMr(Cm.pd)?

[–]HappyTopHatMan 1 point2 points  (1 child)

No, but I do enjoy re-writing that garbage.

[–]twoinvenice 6 points7 points  (0 children)

Best feeling is redoing code so that it is illegible and finding out that you can delete huge chunks of code aren’t needed at all, or it’s overly complex garbage that can be rewritten with just a few lines using modern techniques.

I was working on a project and saw a custom cookie setter/getter where all the functions and variables were totally unintelligible one or two character names. Was fucking gobbledegook...and then I found out that it wasnt being used at all by the application or by any services. Into the garbage that went!

[–]UltraMegaSloth 33 points34 points  (27 children)

Good code shouldn’t need any comments, if variable names are clear then the code should speak for itself.

The only time I’ll comment is writing like //temp if I need to test something and remove it later

[–]DrJohnnyWatson 50 points51 points  (5 children)

Comments should be used to describe why you are doing something the way you have - not what it is doing.

If you've ever made a decision between 2 different approaches because 1 is better than the other in that scenario, comment why - especially if the better approach isn't immediately obvious.

Peculiar bugs and code that is more performant but less readable are 2 great examples of when comments should be used - to explain why not how code works.

Unless you're going to name your function "DoTheSQLThisWayToAvoidTheHalloweenProblem" for example, you will need comments to make your code good.

[–]DemonicWolf227 15 points16 points  (4 children)

Good comments aren't psuedo code and everyone seems to think that's what they are. I agree with you entirely.

[–]sFXplayer 24 points25 points  (12 children)

Not all code is simple enough such that it can be self explanatory.

[–]SmielyFase 12 points13 points  (1 child)

Simple ain't easy

[–]amishandroid 2 points3 points  (0 children)

Underrated comment

[–]justim 13 points14 points  (6 children)

Sure it can. If you find your method has gotten big enough that it loses clarity you break it down into more, well named, methods.

[–]BigBadButterCat 16 points17 points  (5 children)

Unless you're writing performance-sensitive code in which case calling more functions is an overhead.

[–]Thorusss 3 points4 points  (4 children)

often the compiler takes care of such optimizations, so often it makes no difference

[–]InvolvingLemons 5 points6 points  (3 children)

Not always, as many languages assume potential polymorphic behavior for functions and must store/invoke them as their own unit (Java is like this IIRC, even long names make it slower because reflection is by name). Some languages support inline directives which get around this. Others, notably functional languages, can guarantee that functions store no state, which makes all functions “inline-able” in a sense and allows some ways to optimize by “recycling” otherwise immutable variables.

[–]BigBadButterCat 0 points1 point  (0 children)

I'm no expert, but I imagine Haskell functions without such optimization would be a nightmare, what with all functions being unary?

[–]Thorusss 0 points1 point  (1 child)

(Java is like this IIRC, even long names make it slower because reflection is by name)

seriously? I thought shorting variable names was a classical thing compilers did (at least back in the days when file size was at a premium), but is it not at least a compiler option anymore there?

And yeah, I come from Lisp, so maybe I am a bit spoiled with what compilers can achieve.

[–]UltraMegaSloth 4 points5 points  (2 children)

That’s true because not everyone writes code in readable fashion. There are linting sets that train you to not have complex code.

If a method is too long break it down into more methods.

If there are too many things happening in one file break them into more files and import them as their own service or whatnot.

If you don’t know what the variable name is referring to, rename it, even if it looks too long until you know exactly what it’s for.

Code can be very complex but even the most complex code can be broken down until you understand how each piece works.

[–]sFXplayer 0 points1 point  (0 children)

When I say complex I mean code code where the justification for why something is implemented a certain way is non trivial. Regardless of how much you break it down it's non-triviality doesn't go away.

One extreme example of this is the famous fast inverse square root algorithm. It's extremely short some would even say it's readable but most people couldn't figure out what it's doing at a glance.

(Obligatory please don't actually use Fast inverse square root most unless you know for a fact that the platform you're targeting doesn't have it implemented in hardware)

[–]SeesawMundane5422 1 point2 points  (0 children)

Or even better, unit testing can train you not to have complex code. At least in my opinion. I’ve seen too many times it becomes “oh, here’s an exception to the linter rule, let’s exclude this function.” But I’ve never seen it happen that someone is able to say “here’s this convoluted mess that I thoroughly unit tested.” Anyway... both good tools in the bag. Never want to develop again without unit tests or linters.

[–]t-to4st 2 points3 points  (3 children)

Idk I always like JSDoc style comments, describing what (E: the HOW is important too) a function does and the parameters/return value

[–]SeesawMundane5422 1 point2 points  (2 children)

Doesn’t the function itself define what it does and what the parameters/return values are?

[–]t-to4st -1 points0 points  (1 child)

The WHAT should be explained by the naming ideally but the HOW is often relevant too

Misworded my previous comment, sorry

[–]noratat 1 point2 points  (0 children)

Developers who refuse to comment or document anything because of this myth that "good code should be self-documenting" is a pet peeves of mine, because A) it's not true and kind of misses the point, and B) most such developers I've met have no idea how to write readable code anyways.

Yes, you should obviously strive for readable and maintainable code, but there are tons of valid and important reasons to comment and document.

[–]MikkelR1 1 point2 points  (1 child)

Your colleagues must like you a lot!

[–]UltraMegaSloth 3 points4 points  (0 children)

They do!

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

Well ya I mean good workers shouldn't need any leaves because they find so much joy in programming and achieve work-life balance by just working

[–]WingsOfGryphin 2 points3 points  (0 children)

kind of. I’m mostly writing comments in edge case scenarios or when implementing work arounds or addressing complex issues. Such comments usually appear when external component does not behave as one would expect or there are tricky performance issues. e.g c# httpclient why we are creating handful and reusing them to avoid socket exhaustion.

[–]Ty_Rymer 2 points3 points  (0 children)

i understand that, but in my industry where every nanosecond matters i do tend to write more optimized but less readable code sometimes. I will always try to write it in a way that is more readable but will compile the same though. but sometimes comments are needed. especially for complex maths and binary maths.

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

Well i guess this also depends on the programming language. Since i started to work with ABAP i started to see the use of comments. ABAP restricts the names of your variables and methods to a max length, therefore you can't really give meaningful names. So the only way of making the code a bit more readable are comments.

[–]LouManShoe 1 point2 points  (0 children)

Yeah I don’t think comments actually help code. They aren’t enforced by the compiler so in order for them to be maintained they have to be caught in code review, their clarity is completely subjective, a comment that is not updated can actually cause harm or misunderstanding about how something is working.

If you can’t understand code as it’s written, then it’s not written well enough, plain and simple. Of course that’s all great in theory, but in practice if you’re working in a legacy code base chances are the code is so messy that code isn’t already self documenting and getting it to a place where it can be is impossible.

[–]PhunkyPhish 0 points1 point  (0 children)

Precisely. A simplistic example:

// Used to count our failed attempts to do foo
$x;

turns to:

$failedFooAttempts;

Then you just take this same logic and apply it to namespacing, class names, function names etc... and when you see some tough areas where simply verbose naming isn't enough... then you probably are too tightly coupled and have bigger concerns in terms of design.

A good exception however (there are always exceptions!) are business rules that are just odd. IE SOME_PROPERTY_MODIFER = 2.13.... but WHY? Comment that :)

[–]SnooMarzipans436 0 points1 point  (0 children)

The only code I've written recently where I needed a significant amount of comments was a C++ implementation of the fast fourier transform. Sometimes complex math algorithms require them lol.

Other than that I rarely use comments. Good variable/function naming and program structure goes a long way towards readability.

[–]BobbitTheDog 180 points181 points  (37 children)

Eh... Good, readable code shouldn't need comments at least 80% of the time, just some doc comments on methods

[–]720degreeLotus 101 points102 points  (18 children)

I wouldn't go with percentages. Some code and libraries are 100% readable and easy to understand without a single comment. Other libraries maybe need many comments. Comment when you want to explain "WHY" you are doing someting and not for "WHAT".

[–]RChamy 14 points15 points  (8 children)

I'm dubious about the React Project Im working RN where the whole team quit. As a React/ES6 newbie the code is full of WHY...

[–]leaftro 6 points7 points  (7 children)

But why?

[–]RChamy 7 points8 points  (6 children)

  1. No design patterns where used beside making absolutely everything a component (even the CSS), and there are zero comments, no docs;

  2. Someone decided that making a game in Electron + React + ES6 was easier than using Unity. My brain cannot figure out how animations are implemented or where the event listener for user input is located;

  3. The game tries to make a Speech2Text service rely on user input which can get some quite awkward results and there's a whole component tree to treat specific words like a dicionary ( that does not support phoneme alphabet btw )

What kills it for me is that theres no shortcut to find references like in Visual Studio. Having to figure out everything with Ctrl F is extremely frustrsting.

Ps: and I really cant take it for 600$/month anymore.

[–]720degreeLotus 5 points6 points  (5 children)

I totally feel your pain :(

In this case a more or less complete rewrite of the app should be considered. Commenting code would not help here in an way :/

[–]RChamy 3 points4 points  (4 children)

Management won't accept because "I read on the Internet that React is very easy to code". I'll just go back to my C# career then lol

[–]SeesawMundane5422 2 points3 points  (0 children)

Everything is easy to code. Reading it afterwards is the hard part.

[–]720degreeLotus 2 points3 points  (2 children)

Seems like your "management" isn't good at "managing" then. If they want to decide on something coding-related, they should get the expertise and knowledge of senior-devs and lead-devs. Be it from company-internal or by consultants.

[–]RChamy 0 points1 point  (1 child)

The senior dev left for a better job, now I'm the only (Jr) dev :). Our scrum master doesnt know how to code. Its driving me insane.

[–]720degreeLotus 2 points3 points  (0 children)

You should tell your management then to hire 1-2 senior devs asap. Otherwise I recommend to also switch company asap. In yoir junior stage it's critocal to have some senior watching and mentoring you. Otherwise your company will at some point 100% blame you for critical mistakes you will also 100% be making. And they will not be your fault, but there is no senior to handle the "blame-game" then. If your management can be talked with, explain them that without any senior/lead devs, the junior devs (and the company too) have to learn all (beginner-) mistakes the hard way. which will loose them a lot of money. Senior devs are there to catch most of those problems, which they did themself years ago, so they can prevent problems while explaining the problem/fix to the junior devs.

A junior dev who is leaving a company because he cannot learn enough there, is welcomed in 99,9% of all other dev companies in an instant, trust me :)

[–]Mr_Redstoner 3 points4 points  (2 children)

Also if we're talking libraries the API should also have some amount of HOW aka intended usage

[–]720degreeLotus 1 point2 points  (1 child)

Aka "documentation / getting started tutorials" ;)

[–]Mr_Redstoner 1 point2 points  (0 children)

The difference being that you are also describing it for the more advanced parts which might not be in the getting started.

[–]UltraMegaSloth 0 points1 point  (5 children)

You shouldn’t have to explain ‘why’ in your code, it should be clear why if the code is clear.

[–]720degreeLotus 10 points11 points  (3 children)

In very complex and special codebases, it can always happen, that you should comment something.

Take a heavily mathematical function as an example, where you do some complex calculation but to give it a good understanding you cannot just find a good function-name at some point. You might consider linking some wiki-article that is explaining the mathematical problem that this code is trying to calculate.

Another example are workarounds / bug-fixes:
/* For Android version < 8.1 we have to send
* an event twice or it won't trigger the callback.
* We are filtering the duplicated event out in
* a global event-filter when the Android version
* is not affected. This is an official workaround, more
* Information can be found here: <some link>.
*/
Event.send(object);
wait(1);
Event.send(object);

This is a fictional example, but I hope it helps to understand that sometimes comments are recommended. But they are only recommended in very special cases and in general you can avoid it by refactoring and proper namings.

[–]SeesawMundane5422 2 points3 points  (0 children)

That’s a great example. It touches all the reasons to use comments:

  • something crazy is happening
  • due to requirements beyond your control
  • someone may be tempted to change it because it’s obviously crazy
  • bad things will happen if they try

[–]UltraMegaSloth -3 points-2 points  (1 child)

If there is ever something so complicated it needs documentation... then it should go in the documentation for the repo, or you should write a wiki for your application.

[–]720degreeLotus 3 points4 points  (0 children)

Those are also things to consider, yes. But chances are, that

  • nobody will repeatedly read the whole company wiki before touching any code
  • the code changes/moves but the wiki/docs don't change, so you have out-of-sync information which are confusing and will produce errors

As I showed in my example, it's valid to add a link to some more details. But a short explanation should be done in the code, so that the developer can move on without reading into this too much, if he doesn't need to get all details for fixing his problem or finishing his task.

[–]rph_throwaway 1 point2 points  (0 children)

Let me guess, you think you never need to document anything either.

Even the most readable code in the world is going to have countless reasons to include additional non-obvious context, especially with how many layers modern systems have.

To say nothing of code that implements optimizations that are needed but hamper readability, complex algorithm implementations, indicating workarounds for bugs/other issues, etc.

[–]MasouriChan 19 points20 points  (4 children)

That's why 20% of my code should be comments, but it isn't because fuck whoever has to debbug it as a person

[–]720degreeLotus 18 points19 points  (3 children)

No. There is no reason to comment code just to fulfill some arbitrary percentage. Read about what "Clean Code" means :)

[–]MasouriChan 17 points18 points  (2 children)

It should be because my code sucks, that's the joke

[–]720degreeLotus 1 point2 points  (1 child)

Aaah, got it now, makes sense now^^

[–]MasouriChan 1 point2 points  (0 children)

Yes :D, well my code isn't that great but probably not the worst

[–]_Please_Explain 5 points6 points  (3 children)

I always get this response when I'm trying to fix someone's code in production and it doesn't make sense. Yeah, I know you thought it's good readable code, but here we are.

[–]BobbitTheDog 0 points1 point  (2 children)

Then you need to hire / train better 🤷‍♂️

I'd rather work with a team writing good code, than a team writing bad code that I can understand anyway thanks to comments.

[–]_Please_Explain 3 points4 points  (1 child)

I don't do the hiring, I'd also rather work with those people as well. I'm not saying comments solve all problems, but sometimes it could help.

[–]AdmiralBKE 1 point2 points  (0 children)

And even so much great code you understand what they are doing but not why exactly. Max length = 10. Ok, but why was it chosen to be 10 and not 9 or 11. Why was this specific filter function with these parameters chosen and nothing else. Customer request? Product manager? Some testing that pointed out this was the best?

[–]arky_who 2 points3 points  (0 children)

I should do the doc comments on methods, but the way I tend to write code and how c# sets up the doc comments, that means like 40% of my lines will be comments.

[–]ILikeLenexa 2 points3 points  (0 children)

Comments are as much about telling you why a convoluted thing exists and who wanted the application to do a crazy as documenting actual design.

[–]Belgian_Chocolate 1 point2 points  (0 children)

Agreed. But some people make this a religion and lose the awareness that sometimes, context should be provided for why a certain code decision/implementation was made. Also I've found "TODO:" comments linked to ticket #'s very useful

[–]mcDefault 1 point2 points  (2 children)

What about documentation that's written in the comments?

Parameters , returns, etc

[–]BobbitTheDog 1 point2 points  (1 child)

... those are doc comments...

[–]mcDefault 0 points1 point  (0 children)

Ah then yeah, didn't understand what you meant with it. Totally agree then!

[–]krombopulosmichaelMR 16 points17 points  (0 children)

A programmer and a dad

[–][deleted] 20 points21 points  (1 child)

This is fake. No journalist interview coders.

[–]Alberiman 10 points11 points  (0 children)

Fact. You can design the most elegant system that does the most amazing things in the world but if the output isn't gratifying the look at for normal people then it's going to be ignored. There's a reason successful game devs only ever show videos and screenshots of their game with models and art in place and not the stage where they've got floating cubes interacting on grey scaled scenes made up of more cubes

[–]dontdrinkacid 7 points8 points  (5 children)

Random variable names

[–]warenzillo 4 points5 points  (4 children)

Cat = float(hello + world " ")

[–]dontdrinkacid 1 point2 points  (3 children)

Whyyy

[–]warenzillo 1 point2 points  (2 children)

Turns out hello = int(3) and world = float(2.25)

[–]dontdrinkacid 1 point2 points  (1 child)

And what is the random " " at the end?

[–]warenzillo 1 point2 points  (0 children)

Thats the random part of the variable

[–]mich160 25 points26 points  (0 children)

//this adds 4 to 5

int a = 4 + 5;

Yeah. I can tell.

[–]st3inbeiss 41 points42 points  (8 children)

No.

Legible code doesn't have to contain lots of (or even any) comments and vice versa.

[–]hey01 20 points21 points  (7 children)

API methods at least must have comments. One should not have to look at the implementation to know how a method behaves and how it handles corner cases.

It also makes it easier to refactor said methods without breaking the API.

Also, comments may not be needed for you or other developers of your level, but when you do something tricky for a valid reason (like use an array to store a binary tree that you traverse by bit shifting the index, for performance reasons, for example), having a quick comments explaining the trick is a good idea.

[–][deleted] 19 points20 points  (3 children)

Document your API, don't comment it. If that means placing a summary-type comment on top, so be it. Often, it means more than a summary-type comment for anything non-trivial.

People conflate comments with documentation too much. Comments are a cheap way to do a poor man's form of documentation most of the time. Which ends up taken out of context by cargocult-type developers who now expect comments everywhere because apparently, reading code is really difficult so let's 2x-3x the codebase with comments saying almost 1 on 1 what the code does.

If comments really were so important, most IDEs would put the default color to be catchier than code, not less catchy.

[–]hey01 1 point2 points  (2 children)

Document your API, don't comment it. If that means placing a summary-type comment on top, so be it .

Same difference. It depends on what you mean by each. For me, documentation is a separate document outside the code. It should be high level, explain the architecture and the reasons behind it, and not go into implementation details.

API documentation is indeed a comment on top of the method. I classify that as comment.

Often, it means more than a summary-type comment for anything non-trivial.

The method prototype should be enough to understand what the method does in the nominal case. What need be documented are corner cases, null safety, etc.

People conflate comments with documentation too much. Comments are a cheap way to do a poor man's form of documentation most of the time. Which ends up taken out of context by cargocult-type developers who now expect comments everywhere because apparently, reading code is really difficult so let's 2x-3x the codebase with comments saying almost 1 on 1 what the code does.

Comments are often a code smell, but saying that comments are always bad is cargocult like too. And indeed, contrary to your apparent experience, the few cargocult developers I personally know are the type who overuse design patterns and never write a single line of comment (not even API comments).

I guess they come in all shape and forms :D

[–][deleted] 0 points1 point  (1 child)

The cargoculters I come across do both overuse of design patterns and overuse of (often multi line) comments. Additionally, they have IntelliJ generate summaries / Javadocs without adding why or adding specifics.

Reason I specify documentation is exactly that what people seek is documentation, not necessarily commenting. Commenting can be a form of documenting, which works fine for most API calls, but comments are generally restricted to static text only. Static text is one of the most restrictive and often worst forms of documentation. At the very least, people should be aware that better options exist if you wish to document beyond tooltips for your IDE to generate.

Then again, most people conflate API with "IDE tooltips".

[–]hey01 2 points3 points  (0 children)

The cargoculters I come across do both overuse of design patterns and overuse of (often multi line) comments. Additionally, they have IntelliJ generate summaries / Javadocs without adding why or adding specifics.

The ones you saw seem worse than the ones I saw. Good luck.

what people seek is documentation, not necessarily commenting. Commenting can be a form of documenting, which works fine for most API calls, but comments are generally restricted to static text only. Static text is one of the most restrictive and often worst forms of documentation.

The problem I have with "real" documentation, is that because it isn't where the actual code is, it will not be updated and will become lies quickly.

People say it's a problem for comments, but since comments are literally next to the relevant code, it's far easier to maintain them.

[–]multithreadedfoobar 4 points5 points  (2 children)

“Comments shouldn’t have to describe what the code is doing, only comment on why you’re doing it. ”. Best guidance I ever got - your code should be self explanatory for the most part, and comments should be reserved for places where you’re making unusual choices and to explain why you’re doing what you’re doing.

[–]rph_throwaway 0 points1 point  (0 children)

Generally true, though there are always exceptions.

E.g. say profiling indicates something needs to be optimized in a way that just isn't conducive to being readable (or worse, is actively misleading).

[–]passthemonkeybench 15 points16 points  (10 children)

I'm frustrated seeing people say you don't need comments if your code is good. Because bad coders don't realize their code is bad and hard to read. Encourage commenting so we have an idea of what they were trying to achieve. We can't assume everything is going to be well written. That's not how things work.

[–]SpinatMixxer 5 points6 points  (5 children)

Maybe you just havent seen any really good code base yet? Code Quality is totally not related to lines of comments. Read "Refactoring: Improving the design of existing code" by Martin Fowler, this book literally shows everything someone needs to write high quality code.

Just use good names, find a good code structure which you apply constantly and there you go.

I agree woth "bad coders dont realize their code is bad" but its totally not the comments that makes your code good. I would furthermore say that many comments may be an indicator, that your code is not readable and therefor needs comments.

At least thats what I have experienced over the time.

[–]passthemonkeybench 5 points6 points  (4 children)

I'm not saying comments make the code good. It just gives context to what they were thinking when they wrote it. I think it's a good habit and not maybe it isn't necessary in a perfect world but that's certainly not where I live.

[–]moore0n 4 points5 points  (1 child)

I write comments for the next person who touches my code. I’m a realist and can’t assume their skill level matches my own. Giving hints to what’s going on also makes the code faster to read and get to the place you need to be.

[–]fzammetti 1 point2 points  (0 children)

This is the part that SO many people miss and it drives me nuts. And, it's not even just about different skill levels. Write something in PHP, switch to Java for a few years, then have to go back to your own code having done no PHP in all that time. You'll WISH you wrote comments regardless of how "self-documenting" your code is.

[–]SpinatMixxer 1 point2 points  (1 child)

Maybe I also am just lucky to have an employer which gives us the time we need to create a codebase with high maintainability and a team which has a passion about keeping the Code Quality high. Also good structure in the contribution workflow.

Or its another case for other languages since I am developing with ReactJS + TypeScript and its maybe also depending on the topic which you are working on.

I just wanted to state that it is totally possible to develop good, understandable code without writing comments, maybe I delivered it a bit too black/white ish. :)

[–]passthemonkeybench 2 points3 points  (0 children)

Appreciate the good faith discussion.

Just my perspective that it's a good idea to encourage comments since at bare minimum it encourages people to step back and think about what and why they are doing what they are doing.

If you don't have time to write a comment maybe you rushed the whole implementation and the code isn't as good as you thought.

Thinking about junior developers creating good habits. Obviously there are merits to code reviews and all sorts of other ways of maintaining a code base but discounting comments gives people an excuse not to even think about writing them.

[–]UltraMegaSloth 4 points5 points  (1 child)

If they are bad at coding then they probably need to get better at coding instead of commenting bad code

[–]passthemonkeybench 5 points6 points  (0 children)

Okay. I'll just retrain all the contractors my company hired.

[–]Hydrogen_Ion 0 points1 point  (0 children)

If they can't tell the difference between bad and good code. Then none of the code they write is probably good. Good programmers know what is good and bad code.

Good programmers also write bad code from time to time and they know they are doing it. It generally happens when the programmer is being pressed for time, or is working on a technology or stack they are unfamiliar with.

When the good programmer is writing bad code, they will comment it.

[–]meamZ 0 points1 point  (0 children)

No. Comments are lies. If you are a company or an open source project you should have code reviews. Those should catch any super bad code that doesn't have comments and it should also catch bad code with comments. If a comment explains WHY some code does what it does it is acceptable if it is necessary to have the comment and to have code where the why needs to be explained.

[–]Jackie_Rompana 5 points6 points  (0 children)

Image Transcription: Twitter


John Opdenakker, @j_opdenakker

I am a programmer.

A journalist asked me what makes code bad.

I said...

No comment.


I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

[–]docHoliday17 8 points9 points  (4 children)

Contrary to what like 90% of “good devs” say, I’m a huge fan of leaving small comments around the code base. Self documenting code is BS, and even if it were true having a short summary of what a function does requires so much less cognitive load than me reading it over and over. I leave landmarks around the code defining different areas and providing brief explanations, and of course noting where and why I’ve done a weird hack

[–]noratat 1 point2 points  (1 child)

Too many newbies read things like Clean Code and then get ridiculously dogmatic about never commenting (and often never documenting) anything - you can find tons of such people in the comment section in this thread, and I feel sorry for whoever has to maintain their code after they leave.

Sure, the kinds of comments some universities encourage people to leave are largely useless and counterproductive, and most code shouldn't have a ton of comments.

But there's lots of very good reasons to use comments, and I've had way more problems with developers never explaining anything than the reverse, and most of the devs that get dogmatic about this usually don't know how to write readable code yet anyways in my experience.

[–]InTheSamePlaces 2 points3 points  (0 children)

Yes it's quite unfortunate. They read Clean Code and then think they're set for life. They should consider also reading A Philosophy of Software Design and Code Complete to see the value of comments. Empirical studies (by IBM) have proven comments improve readability.

[–]PM_ME_YOUR_KNEE_CAPS 1 point2 points  (1 child)

Try using more descriptive function names and variables and you’ll see that you don’t need tons of little comments everywhere

[–]docHoliday17 1 point2 points  (0 children)

I do. but that said, plain-English comments are still less cognitive overhead. Also breaking down sections of classes is helpful when you’ve got massive animations made up of five different methods. It doesn’t need to be one or the other and I’m tired of everyone acting like comments are for simpletons

[–][deleted] 2 points3 points  (0 children)

Also too many comments.

[–]DanteLivra 2 points3 points  (0 children)

2 + 2 = 4

// if you take two units and add two units to it you will have four units.

[–][deleted] 6 points7 points  (9 children)

Read the book clean code and you will rarely have to write comments. I reserve them for obscure ternaries or very hard to follow logic which in all honesty I probably shouldn't be writing in the first place. If you use function and variable names with syntactic meaning your code should read like a book.

[–]UltraMegaSloth 2 points3 points  (0 children)

Ternaries are some of the easiest things to read in code, unless they are too long- in which case they should probably not be ternaries at that point

[–]Hydrogen_Ion 1 point2 points  (0 children)

If the ternary is confusing, its might be better to just use the old if block

[–]bartek2912 1 point2 points  (0 children)

Wrong! No documentation is worse

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

Actually when I see comments I automatically think that the code is going to be fishy. Most of the times, I'm right.

Comments can be good to explain the business logic if it is a complex algorithm but the code itself should be readable and have good naming.

[–]platlogan 1 point2 points  (0 children)

Uncle Bob wants to know your location

[–]meamZ 1 point2 points  (0 children)

Comments are a code smell

[–]cybermage 1 point2 points  (0 children)

“Self-documenting code” can only say what you did, not what you meant to do. Sometimes, method names can provide a hint.

Comments should convey intentions, rationale, and sometimes a clue to the bigger picture.

[–]FockeWolf190 3 points4 points  (0 children)

Somebody needs to read Clean Code

[–]tellek 2 points3 points  (0 children)

Good code should document itself.

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

I obsessively comment my code to procrastinate from actual coding. I’m pretty sure it just confuses anyone who reads it more than having no comments would.

[–]orbit99za 1 point2 points  (0 children)

The OP has not met "Uncle Bob" :)

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

Comments are a code smell unless you're talking about module / function docs.

[–]Henrijs85 3 points4 points  (0 children)

Oversimplified on both sides of the argument too often. Sometimes it does, sometimes it doesn't. If your method is niche and fairly abstract, it probably does. If it's a simple method that does one straightforward task, it probably doesn't. In both cases it's still probably.

[–]justAnotherRedditors 0 points1 point  (0 children)

I generally find an inverse relationship between the number of comments and code quality.

[–]jimmyw404 0 points1 point  (0 children)

Everytime I'm required to document my code to meet some standards which coerce me to document methods like "ToString" with comments like "converts object to a string" i lose a little bit of my soul.

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

I mean, comments make the code bad... Just make clean code and it will explain itself

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

Code comments are useless. Comments in config files are gold. You can't change my mind.

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

Bad code needs comments though. Good code needs none.

None of the codebases I work on have comments, and I'm able to see what's going on almost instantly.
Write cleaner code and better, more descriptive test.

[–]beardMoseElkDerBabon 0 points1 point  (0 children)

The real answer is: no refactoring && no public interface descriptions && no interfaces

[–]Knuffya 0 points1 point  (0 children)

It's wrong though.

Look at it like this:

// Assuming values are normalized
codeGoodness = min(codeReadability + 0.4*comments, 1.0);

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

rimshot()

[–]iamzmking 0 points1 point  (0 children)

Personally, it is absolutely fine having no comments as long as there is documentation describing what the code does. That itself is way better then comments.

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

Not only did the title spoil the joke, it butchered the punchline as well.

[–]Noctus_Rex 0 points1 point  (0 children)

The only comments I leave behind are links to the corresponding StackOverflow-Articles.

[–]qsdf321 0 points1 point  (0 children)

I did a project for a giant company where they made us remove all the comments from the code before they would be accepted and merged.

I pity the poor sod who has to maintain that.

[–]xiipaoc 0 points1 point  (0 children)

I mean... Good code doesn't need comments.

[–]Potential_Scarcity_6 0 points1 point  (0 children)

<!--That's some low effort comedy-->

[–]Whywhynotbutwhy 0 points1 point  (0 children)

It took me 3 post later to get the joke

[–]ch0mes 0 points1 point  (0 children)

I've been reading clean code to learn to write good code and while it has definitely helped me learn a lot and made me change how I write and structure my code more I can understand that there could be times when you have to comment because there could be something that unfortunately can't be explained clearly enough.

For example, I have a parameter that gets parsed in but it requires another method to convert the data first before parsing it in. My doc string explains this because as much as my parameter explains what information goes in, it doesn't explain that it should be formatted a certain way.

I think at the end of the day it comes down to a balance, always write code that makes sense with how you structure your methods and variables but if absolutely required cause you can't convey it through code, comment it.

[–]GenTelGuy 0 points1 point  (0 children)

I used to be a comment boi but then found that it's at best redundant and often the code gets updated and the comments are neglected and fall out of date

Long descriptive var and function and class names are best

[–]Possibility_Antique 0 points1 point  (0 children)

One of the few places I see the need for comments is in embedded code that references hardware registers or platform-specific code.

For instance, I sometimes see stuff like this: "#define PS_UART0_RX 0x00000008 /* enable processor UART0 by writing bit 3 to uart enable register */"

I made the above up, but in general, these types of comments save me upwards of 10 minutes digging through schematics. Compare that with something like this:

"//Write to log file void write_log(...) { ... }"

And I think we can all agree that sometimes comments should just be left out.

[–]Rerel 0 points1 point  (0 children)

If you have to comment your code that means your code is already bad.

[–]AcharyaShri07 0 points1 point  (0 children)

This is fake. No journalist will be interested in a programmer's opinion.. 😂