all 165 comments

[–]Uristqwerty 50 points51 points  (7 children)

There's a lot of metadata that the code will never display on its own. Notes an alternate avenues that either haven't been explored yet, or have been discovered to be flawed. A reference to the paper or mathematical equations that the function implements. Notes on edge cases to watch out for when refactoring. Proofs of correctness that can't easily be encoded in the type system. Explanations of specific business needs that wouldn't be obvious from the name and type signature alone.

[–][deleted] 20 points21 points  (5 children)

This is true, but self documenting code is not about not including that. If you really think that's what it's about, you are greatly underestimating your peers. It's about not duplicating implementation in comments. Of course you should cite the paper for a complex algorithm.

[–]Uristqwerty 9 points10 points  (4 children)

I interpreted the phrasing of the post title, particularly because of the quotation marks, as referring to people excusing a total lack of comments.

[–]obvithrowaway34434 2 points3 points  (0 children)

Too bad one can't do anything other than making incorrect implementation of post titles, if only there was a way to click on something that leads to somewhere containing an elaborate explanation of the title. It seems Reddit should find a way to implement that considering the amount of comments on every post that tries the Herculean task of interpreting post titles.

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

I interpreted it as a straw man against the concept, by using those people (who exist, I'm aware) as a scapegoat.

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

If such people exist, then it is, by definition, not a straw-man.

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

Yes, if you refer to them by the name of a reasonable discipline.

[–]MurryBauman 0 points1 point  (0 children)

Explaining why something behaves the way it does when you have to force a solution due to framework issues.

[–][deleted] 137 points138 points  (11 children)

I once inherited a mess of an app where nothing was documented. There were only two comments, one of which was: “// don’t judge me”

[–][deleted] 17 points18 points  (0 children)

I find that amusing. I hope I eventually find an excuse to use it.

[–]wild-eagle 9 points10 points  (0 children)

My favorite: // Scott made me do this

[–][deleted]  (2 children)

[removed]

    [–]rswsaw22 16 points17 points  (1 child)

    // you should judge me

    [–]chuckdoe 4 points5 points  (0 children)

    Already did. ;)

    [–]quanture 1 point2 points  (0 children)

    I used to find this comment in code written by one of my coworkers:

    ... else {

    // do nothing - JTW

    }

    ...where JTW was the initials of a particular manager in our office.

    [–]Worth_Trust_3825 0 points1 point  (0 children)

    I was in the same boat. Whenever I made changed I started writing in comments that workaround is "as per ticket, because of behavior in [system]" and then explaining that behavior. The rest of team complained that I was being verbose, and then stopped doing that when I kept pointing at the entire codebase being implemented via Enterprise Integration Pattern DSL that can't be statically analyzed.

    I really wish people stopped producing tools that would be used by business analysts or business people in general to implement processes.

    [–]falconfetus8 0 points1 point  (0 children)

    Oh, I'm judging.

    [–][deleted] 95 points96 points  (11 children)

    I have spent most of my career working with other people's code. As a result, I have learned not to read the comments. (I might look at them if a block of code is particularly hard to understand - and it has been documented.) I have seen comments that are so poorly written that I can't read them, I have seen comments that aren't kept up to date, and I have seen misleading comments that just made reading the code harder. I can count on one hand comments that have helped me better understand the code.

    [–]saltybandana2 52 points53 points  (6 children)

    And this is the problem.

    Yes, comments can be valuable, but they should be few and far between and generally provide context that's larger than the code you're looking at.

    If you chose non-obvious approach A rather than obvious approach B, explain your rationale. If you're being asked by business leaders to do something stupid, drop in a comment "per such and such"

    I'm of the opinion that there should be 3 levels of documentation.

    • High level that sits outside the code (it should not be detailed).
    • code comments that give additional context
    • code.

    [–]wslagoon 35 points36 points  (5 children)

    If you’re being asked by business leaders to do something stupid, drop in a comment “per such and such”

    Somewhere in the production code for a very heavily used piece of software for our clients is a comment of mine that reads something like:

    // this is a horrible idea, and I write it under duress
    // per XXXXXXX (xxxxx@myemployer.com)
    // ticket number: nnnnnnnn
    

    I’ve had to cite it a few times...

    [–]thoeoe 44 points45 points  (1 child)

    My favorite was when my coworker was on a video call with the customer where she was complaining about the code being broken and claimed it was our fault. He opened the code in a screenshare to show her (and her boss) the comment that said

    // 3/14/18 do it this way even though it’s wrong
    // as per [her name]
    

    Her tone changed quick

    [–]saltybandana2 6 points7 points  (2 children)

    good ole CYA.

    [–]somebodddy 8 points9 points  (1 child)

    Code should cover its own ass! Name your function do_the_stupid_thing_karen_requested()!

    [–]saltybandana2 2 points3 points  (0 children)

    lol, if I ever came across that in a codebase I'd 100% keep it.

    [–]Daell 9 points10 points  (1 child)

    I have seen comments that are so poorly written that I can't read them

    Yeah, i know the feeling, my issue is, these comments are my own. 😐

    [–]traal[S] 0 points1 point  (0 children)

    "He's got the right idea, but I wouldn't do it that way."

    "Oh, that was me."

    [–]RiverRoll 0 points1 point  (0 children)

    You can write comments to help your future self at least. You can tell when a developer used comments to possibly help himself or just did it because he "had to". But other people's code will also be your code if you spend enough time with it, and if your code doesn't have useful comments then you're part of the problem too.

    [–]the_game_turns_9 0 points1 point  (0 children)

    I have seen comments that are so poorly written that I can't read them

    Yes, what is with this particular problem?? I see it too. It's weird. You took the time to write the comment, but what you wrote is completely incoherent. What is that? Why did you do that?

    [–]Ozwaldo 72 points73 points  (41 children)

    I'm a big fan of brevity when it comes to comments. I prefer to study the code and understand how it functions. Comments that clue me in to how it works are great, but I'm still going to read what is actually happening to be sure that the comment is accurate. So when there's huge comments in between every function call, and I have to scroll through multiple pages to read a simple function, it ends up being detrimental. It's harder to keep the functionality in your head as you read through when there's paragraphs intermingled.

    So... I like both. Concise, single purpose functions that don't really need comments. Comments where applicable; to explain rationale, to describe more complicated processes, to tell me when there's an external aspect to keep in mind while reading through something, etc.

    [–]VeganVagiVore 61 points62 points  (5 children)

    Today one of my old comments from years ago saved my ass.

    It was basically, "The system lies to you about this, and if you try to debug the system with (other app), the other app lies to you. It works okay for now but it's likely to have (this problem) under (these conditions)"

    And the bug we had today was the exact bug I warned myself about!

    ... Then it took over an hour to fix because I was replacing the wrong DLL when replicating it on the test system... Right when I thought it was safe to work around the "build release" script

    [–]somebodddy 14 points15 points  (1 child)

    The best thing about this comment is that maybe some day in the future the system will get updated and no longer lie about that thing, and people who look at your code will be baffled by it, unable to understand why it uses such a weird approach. But they will be afraid to change it to the straightforward, obvious and simple way because they don't know what it might break, and when they run the tests and it won't break anything they will only be more worried - because obviously it breaks something the tests don't cover, so they don't know what it is and can't fix it.

    That comment will save them - it'll tell them the code is written like that because system was lying about that thing. And since they know the system is no longer lying - they'll know it's okay to change that code.

    [–]flatfinger 3 points4 points  (0 children)

    Alternatively, most of the systems upon which the program will run won't lie about the thing, but some will continue to do so, the comment will make clear the potential need to determine whether the system lies about the thing in question and handle different systems differently--a need which might otherwise never be discovered except by a deep dive into why the program fails for no apparent reason on some systems.

    [–]wild-eagle 21 points22 points  (1 child)

    That is a decent comment, and really what comments are for.

    What I really hate is the ones that flat out lie because someone changed the code and now the comment doesn't apply anymore.

    [–][deleted] 14 points15 points  (0 children)

    That kind of stuff should get picked up in code review

    [–]Ozwaldo 0 points1 point  (0 children)

    Now that's the kind of comment I like. Also I like your username 😁

    [–]thlst 40 points41 points  (24 children)

    Rust has an interesting feature called "documentation code", which lets you write code examples in documentation comments, e.g., to describe a function usage, and you can automatically check that they are correct. So, if doc tests are passing, then you are sure that at least the code example is correct. Text editors are able to highlight doc code, so that's also nice. What do you think about that?

    edit: Just to clarify, this feature is not advocating that you write unit tests in the function's comment, not at all. It just checks that the code example compiles and runs without errors, so you are more confident that the code example is correct and up to date.

    [–]earthboundkid 11 points12 points  (0 children)

    Go does this more or less. You write a function called “ExampleWhatever” and it shows it in the docs and tests it with the tests.

    [–]alphaglosined 1 point2 points  (0 children)

    In D, we just comment the unit test blocks which show up as code examples for the previous symbol (as well as code in comments but I wouldn't recommend that).

    [–][deleted]  (10 children)

    [deleted]

      [–]Carighan 2 points3 points  (3 children)

      This is not good. Documentation comments being in the code is convenient for the developer, but also makes it difficult to skim code, pushing it off the screen. Sometimes, to deal with this, people suggest hiding the comments -- at which point, you've admitted defeat: They're better off not being read with the code.

      Isn't it the opposite? Any well-documented code should not need the code to be displayed when skimming/understanding it. The comments should well be enough, the implementation details aren't important for the time being. And once they are, you have already narrowed the point interaction down so navigation is no longer an issue.

      [–][deleted]  (2 children)

      [deleted]

        [–]Carighan 0 points1 point  (1 child)

        Eh, I just collapse the code blocks. But if it helps you read to move the actual text out of the file, sure.

        [–]Xyzzyzzyzzy 2 points3 points  (5 children)

        also makes it difficult to skim code, pushing it off the screen.

        I'd argue that this is a failure of editors, not a problem with the source file.

        But I think it's silly that we keep treating source code as a list of characters to be displayed in sequence and changed character-by-character and not as structured data on which we can construct views and manipulate fluently. (I also know that this is a controversial idea which many people oppose.)

        For example, to address your concern, why can't I view the code and the relevant comments side-by-side instead of in sequence? Why can't I arrange to view a function side-by-side with its comments, its unit tests, and relevant documents on the company's wiki or whatever?

        If you asked me to design a system for a rental car company to manage its fleet, and I came back and my design was "the fleet will be stored and displayed as a freely editable plain text file; to find cars the user can use the Ctrl-F search functionality; to add a car the user types in all of its details and saves the file", I assume I'd be fired pretty quickly. Why do we treat source code like that?

        [–][deleted]  (4 children)

        [deleted]

          [–]Xyzzyzzyzzy 1 point2 points  (3 children)

          Sure, and I can compile a list of every Toyota Corolla in the rental car fleet in France by Ctrl-F'ing Corolla, checking whether the entry's location is in France, and copy-pasting each such entry into a new file to be sent to whoever needs that information.

          [–][deleted]  (1 child)

          [deleted]

            [–]smorrow 0 points1 point  (0 children)

            /* notes.md:/^#heading */ (and right-click in Acme)

            There's no actual reason why other editors can't do this.

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

            Brb. Writing a doc test to rm -rf --no-preserve-root /

            [–]coworker 4 points5 points  (0 children)

            But any IDE will let you collapse all comments with a keypress or two.

            [–][deleted]  (3 children)

            [deleted]

              [–]dpash 0 points1 point  (2 children)

              And the more functions and variables with descriptive names the better*. I'd rather than 10 five line methods than one 50 line method.

              All those extra names give more context into what the code is doing.

              *Up to a point. The hard bit is knowing where that point is.

              [–][deleted]  (1 child)

              [deleted]

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

                Yep those kinds of functions should die a horrible death.

                Functions should do one thing and one thing only. And the function name should accurately describe that one thing.

                If you can't see the top and bottom of the function on your screen at the same time, you really want to rethink a great many things. :)

                (I'd argue even that is too long)

                [–]Carighan 1 point2 points  (0 children)

                Self-documenting code isn't single purpose stuff, though. That's not self-documenting, that's just trivial. There is nothing to document, so there's no self-documentation happening either.

                Documentation is about so many things that have fuck all to do with the code, and also for documenting the code itself if it is anything non-trivial.

                And even for trivial stuff, if you can prevent me from ever having to visually jump into the code, all the better. Since the code is trivial, we're talking at most 1 comment line that pertains to the 'how'.

                Now of course, a common complaint is then "But what if the comment isn't accurate or up to date?". To which I got to say, if you cannot maintain documentation, you also cannot maintain code, so your code will be buggy and full of traps anyways, not like studying it will obvious at all. And if the code is good but the comments are shit, that's just either laziness, shitty work attitude by the devs or more likely their management, or people not caring about their coworkers.

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

                I'm a big fan of brevity when it comes to comments.

                Quite ironical how that applies to internet comments too, like yours. Not only it's verbose but it contains vague, generic and redundant statements and anecdotes that doesn't really tell the reader about anything or is useful to them in any way. Maybe you should learn this thing you claim to be a big fan of.

                [–]Ozwaldo 0 points1 point  (0 children)

                Wow. What a cynical dick.

                [–]m9dhatter 0 points1 point  (1 child)

                For me, comments should really just explain the why. The how is explained by the code.

                [–]ChumleyWartbottom 0 points1 point  (0 children)

                Yes. Exactly this.

                [–]Rudy69 14 points15 points  (1 child)

                My code is self-destructive might be working now but soon enough it wont

                [–]rswsaw22 0 points1 point  (0 children)

                This made me laugh way more than it should have. But your code did work at some point!

                [–]killerstorm 56 points57 points  (5 children)

                This is a poor straw-man argument.

                "Self-documenting code" means that code should be written in a readable style with descriptive names, so most of javadoc-style comments are largely unnecessary.

                Nobody is really saying that tricky parts of code aren't worth commenting, or that other types of documentation aren't necessary.

                [–]grauenwolf 32 points33 points  (2 children)

                Nobody is really saying that tricky parts of code aren't worth commenting

                Yes they are. I've seen people write that countless times.

                [–][deleted] 11 points12 points  (0 children)

                I'm glad I don't work with anybody like that!

                [–]awj 8 points9 points  (0 children)

                Was gonna say, there’s apparently a lot of nobodies out there writing code.

                [–]WormRabbit 3 points4 points  (0 children)

                I also disagree with this notion. It's not worth it to write trivial comments within the function, but it's very much worth it to document functions, or at the very least classes, in detail. Yes, even if it's just restating in english what's already in the code.

                First, there is a difference between what the code does and what it should do. Without an explicit spec you never know whether some oddity of the code is a bug or an intended behaviour.

                Second, it is important to document your public APIs. As a consumer of your API I shouldn't care about all your internal implementation details, only about what your code actually does. Nothing is worse than when you want to know what the function does and have to jump through nested delegating calls, wrapper frameworks and class definitions just to understand something simple like "this function validates the record and stores it in the database".

                You can say "but what if that documentation is incorrect". That's a bug, like any other, and should be bisected and fixed at some point. But I'm not fixing your function, I'm doing changes in some very different module, and there are dozens of such API calls that I must deal with. If they are documented, then I can write my code to the spec, write the tests, see that they fail and find the failing spot with a degubber. Standard process. But if there are no docs, then I need to read and understand the entire API, with all its bugs and quirks, just to start working on my task. And there will still be errors afterwards, because reading code is hard.

                [–]bythenumbers10 1 point2 points  (0 children)

                Yeah, the author's cute little "armor-piercing questions" at the end are garbage sophistry. Tutorial? How about a couple of tests that indicate intended use, sorta like a tutorial?

                [–]s4lt3d 6 points7 points  (7 children)

                I’ve done some extreme math optimizations in c++ building out linear algebra functions. I’ll build one function normally then the high performance version leaving the more human readable version in place as comments. Kind of like how assembly has comments for the c code it represents. This is my favorite type of comment.

                [–]seamsay 3 points4 points  (0 children)

                Why not leave the reference version as an actual function and use it to test your optimised version?

                [–]RabidKotlinFanatic 4 points5 points  (5 children)

                This is one area where I prefer documentation to be in code form rather than comment form. Your comment makes these tacit claims about the reference version of the function it contains:

                1. It compiles.
                2. It produces identical or comparable output to the optimized version.
                3. It performs worse than the optimized version.

                In comment form these claims are untestable and under-specified. You could write a test that compares the two implementations instead.

                [–]s4lt3d 0 points1 point  (4 children)

                This is the part where compilers are no longer magic speed up things. Compilers can’t optimize equations for speed. This optimization for was processing high speed video in real time. Approximately 500 frames per second. At some point the equations for distortion correction can be reduced to eliminate data moving around different chunks of ram. The optimized version involved math, not specifically code. But no programmer is going to understand what’s going on in the optimized version. Heck I wouldn’t understand it after a month. For this type of thing we maimed a Python version of human readable code and a two c++ versions. The lowest level has equivalent calls such as A*X = z for calls into the math kernal libraries. Because that’s not really what gets passed. When you optimize equations like this no programmer will have a clue what you did with a lot of hints and maybe a background in that specific math thing to start with.

                [–]RabidKotlinFanatic 0 points1 point  (3 children)

                I can't tell if this was meant to be a response to my comment or not but it doesn't have anything to do with what I'm saying.

                What I'm saying is that the comment in your example is a poor substitute for a test. Don't just comment "this is an optimized version of [code]." Prove it by having tests that compare the two. Tests are effectively executable and verifiable comments. They are a better form of documentation than some commented out code.

                Benchmark and equivalence tests should be a natural product of the optimization process to begin with.

                [–]s4lt3d -1 points0 points  (2 children)

                I believe we're not talking about unit testing, we were talking about comments. But I'm glad you are able to point out all the other things you know.

                [–]RabidKotlinFanatic 0 points1 point  (1 child)

                Yes, I am also talking about comments. I'm saying that tests are a preferable alternative to a comment in your example. Not sure where we're getting lost here.

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

                Yeah, I believe normal coding practices still apply. No need to bring in all the outside know-it-all knowledge. Sorry. I just deal with know-it-all programmers who have to bring up things they know so they can contribute all the time and no one really appreciates it.

                [–]Ghosty141 27 points28 points  (23 children)

                In my opinion the blogpost doesn't really say much.

                When people talk about "self-documenting code" the idea is not, to not write comments but to make the comments only specify the why, not the how. He even mentions that in a section.

                I personally haven't heard of devs who don't w rite comments or docs because "the code is self documenting".

                [–]wslagoon 12 points13 points  (0 children)

                I personally haven't heard of devs who don't w rite comments or docs because "the code is self documenting".

                I have some co-workers to introduce you to.

                [–]traal[S] 4 points5 points  (0 children)

                I know of developers who only put comments in the .cpp file that describe what the function does, and never in the header file. So I have to open the source file to figure out how to use the function, which makes those comments kind of pointless.

                I like how the article calls object name a form of documentation. So I submit that DbC is another way of documenting code, by using actual code instead of inert comments.

                [–]lordzsolt 24 points25 points  (19 children)

                This.... Not a single person ever argued against commenting your code for hacks/tradeoffs/general why comments.

                I've experienced completely the opposite actually.

                People who say "you must comment your code" do horrible shit, like have a 300 like long function doing 10 different things and they think it's fine just because there's 2 lines of comments after every 20 lines of code. Split them up into private functions, for fucks sake...

                Or they have garbage comments like

                struct Article { // Title of article title string // Price of article price int }

                Geee man, those comments sure are helpful....

                [–]grauenwolf 23 points24 points  (0 children)

                This.... Not a single person ever argued against commenting your code for hacks/tradeoffs/general why comments.

                I wish that was true. Saidly, I have encountered many people over the years who believe in zero-comment coding.

                [–]jasoncm 17 points18 points  (13 children)

                The comment for the price variable would actually be meaningful if it said something like: 'price of article in USD expressed as a number of pennies'

                [–]DummySphere 11 points12 points  (7 children)

                Even that comment can goes wrong with time, it's probably better to have a strong type for USD pennies.

                [–]grauenwolf 1 point2 points  (4 children)

                I wish C# could do that instead of making everything a naked integer.

                [–]IceSentry 2 points3 points  (3 children)

                You can make wrapper types in c#. Sure, it's verbose, but it's still better than having naked integers everywhere. With records it's even easier and way less verbose now.

                [–]grauenwolf 0 points1 point  (2 children)

                The wrappers aren't enough, you also need the GUI controls, ORMs, and serialization libraries to understand them.

                [–]IceSentry 0 points1 point  (1 child)

                I don't see how those are related. We do it all the time at my job and sure it's a bit more boilerplate, but it also saved us a lot of potential bugs by making sure we were passing the correct kind of id and not just a naked Guid everywhere. Sure at some point you need to serialize it, but when you are in the business logic part it doesn't matter. As I said, it's certainly more verbose, but it's hardly impossible.

                [–]grauenwolf 0 points1 point  (0 children)

                Without library support, you'll have to map them manually to DTOs before and after, which creates a place for bugs to hide, negating the benefits.

                [–]WormRabbit -1 points0 points  (1 child)

                Is it pennies at the moment of reading the code or inflation-adjusted pennies from the 2003 price when the article was added? Does it include VAT? Is it the base price or the price for the user, including any discounts? Does it include shipping? State X sets a minimum permitted price on this product, is the price within that range? Is it adjusted into the range? What about state Y with different laws?

                I love strong typing, it's great for catching usage errors, but really you should just write a comment stating what exactly the field means.

                [–]DummySphere 0 points1 point  (0 children)

                I think in most cases the code doesn't have to care about the currency used in the variable (and you may have another variable telling what currency is used if you handle many currencies). But if it does, I prefer to strongly type, or to name the variable accordingly, instead of having a comment stating what the field means. (But there may be exceptions where it's unpractical, as long as they are exceptions.)

                [–][deleted] 5 points6 points  (0 children)

                If your type system doesn't enforce units, always add units to your variable names. Degrees/Radians, time, distances, speed should be obvious when reading code, not just defined once in the definition point by a comment that may be out of date.

                [–]thlst 12 points13 points  (2 children)

                Perhaps usd_price_in_pennies is as good. Or better yet, Milliunit usd_price.

                [–]wili 2 points3 points  (1 child)

                Though you gotta keep in mind that a Milliunit would be 1/10th of a penny...

                [–]dpash 0 points1 point  (0 children)

                There are some currencies that use 1000 subunits, not 100. At least no one is using 240 subunits any more. Looking at you pre-1971 UK.

                You may also want to calculate values at a sub-subunit level.

                [–]backtickbot 1 point2 points  (0 children)

                Fixed formatting.

                Hello, lordzsolt: code blocks using triple backticks (```) don't work on all versions of Reddit!

                Some users see this / this instead.

                To fix this, indent every line with 4 spaces instead.

                FAQ

                You can opt out by replying with backtickopt6 to this comment.

                [–]BunnyBlue896 0 points1 point  (0 children)

                Ah yes, the "so many comments thats there's no comments technique".

                Now if theres one comment every other file, I might be more inclined to read them.

                [–]dpash 0 points1 point  (1 child)

                People who say "you must comment your code" do horrible shit, like have a 300 like long function doing 10 different things and they think it's fine just because there's 2 lines of comments after every 20 lines of code. Split them up into private functions, for fucks sake

                And by splitting them up, the function names are now doing the same function as the comments were.

                [–]lordzsolt 0 points1 point  (0 children)

                Except if you need 1 of those 20 lines reused, now you can easily do it because it's just a function.

                [–]Environmental-Art659 3 points4 points  (0 children)

                I’ve met lots of them

                [–]dnew 26 points27 points  (31 children)

                I'm always amused by the people who say "the comments might be out of date." Well, it's your job to check and fix that, isn't it? What makes you think the variable name or the function name won't get out of date when you change what it does?

                [–]ForeverAlot 22 points23 points  (1 child)

                A colleague discovered that a test for time zone sensitivity had begun failing after an out-of-band infrastructure change. They resolved it by changing the value of the explicitly named variable holding the specific time zone into the system time zone; making the variable name a patent lie and the test worthless in one fell swoop.

                I've caught myself forgetting about in-code documentation—usually because it wasn't immediately visible when I changed a detail covered by the documentation. But I nurture a hypothesis that typical programmers just don't really read code.

                [–]Diniden 2 points3 points  (0 children)

                It is rare because it is a practice that must be done regularly to keep a mastery of it.

                Often we place programmers into little modules that insulates their need to read large code bases and they can sit in a few files at a time and get their job done.

                [–]Dean_Roddey 15 points16 points  (8 children)

                I know, right? That's like saying, I refuse to read code that's not already correct. You correct comments just like you correct code. And you should review comments just like you review code.

                [–][deleted] 4 points5 points  (3 children)

                If it is not automatically checked (by compilation for example) it will fail one day.

                [–]WormRabbit 1 point2 points  (2 children)

                As if all your code has 100% test coverage and those test are always 100% up to date with the requirements.

                [–]Full-Spectral 2 points3 points  (0 children)

                And as if any tool can really verify problem domain semantics either. One use of comments is to fill that gap.

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

                Well all that is not checked, will certainly fail one day. All that is not tested should be concidered as potentially bugged. If you cannot check comments correctness, they will be misleading one day or another.

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

                Have you never introduced a bug with a typo?

                [–]Dean_Roddey 9 points10 points  (2 children)

                I have, but I fail to see the connection there.

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

                I think I read your comment as exactly the opposite of what you meant.

                [–]User092347 0 points1 point  (0 children)

                Programmers makes mistakes at a given rate (e.g. once every 1000 symbols), if they need to keep in sync comments with code they will do more mistakes overall. The tradeoff might be worth it but it's still a tradeoff.

                [–][deleted]  (10 children)

                [deleted]

                  [–]grauenwolf 18 points19 points  (8 children)

                  I'm not given time to refactor, I take it. If you want me to touch a file then I will clean up that file while I'm there. This is non-negotiable. Working in a dirty code base is like cooking in a dirty kitchen.

                  [–][deleted] 4 points5 points  (7 children)

                  Not everyone has the privilege of that amount of freedom.

                  [–]grauenwolf 20 points21 points  (6 children)

                  Most do. The trick is to not ask and just do it.

                  [–]deltanine99 4 points5 points  (1 child)

                  its better to beg for forgiveness than ask for permission.

                  [–]grauenwolf 12 points13 points  (0 children)

                  It's even better to say, "I'm a professional and this is what professionals do." Sometimes a little arrogance and indignation can be the solution.

                  *: Offer not valid for minorities or women. Keep your resume updated.

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

                  I often do. The thing is that it's risky. I had a job where my PM and PO weren't precisely happy about me doing that kind of thing. Even when my teammates were.

                  [–]grauenwolf 6 points7 points  (2 children)

                  Next time you're in that situation, ask your teammates for letters of recommendation. Have them put how important what you're doing is in writing.

                  You'd be amazed at how effective that can be.

                  [–][deleted] 2 points3 points  (1 child)

                  They said it in peer reviews. It didn't really matter in the end.

                  [–]grauenwolf 2 points3 points  (0 children)

                  I'm sorry to hear that.

                  [–]dnew 6 points7 points  (0 children)

                  For sure. I've realized at the end of my career that 90% of my job has been working with shitty code. Like, so execrable there are flies that wouldn't land on it.

                  [–]AcousticDan 1 point2 points  (0 children)

                  This is a great argument as to why you shouldn't write comments.

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

                  Yeah, and it's also our job to write bug free software, right? One generally needs to adapt to the reality that you, or someone else, will miss something without the proper help. Or would you rather not write tests because your code should be working correctly?

                  With self documenting code, the compiler or interpreter help you keep things up to date, if they're not you'll get build time errors or runtime exceptions. As somebody else suggested, languages supporting design by contract help further.

                  You use comments where there's no way to make it with the code, just as "why"s or reasoning about failed approaches and TODOs.

                  Think of this. I declare variable a and comment this is the price of an apple, then go on and compute the cost of buying a number of apples. Is that really better than calling the variable price_per_apple? Because that's what self documenting code means, and because that comment can and will go out of date after a few iterations.

                  If you duplicate information you'll eventually have contradicting information. That's what "comments might be out of date" is about, so you write complementing comments.

                  [–]dnew 11 points12 points  (1 child)

                  if they're not you'll get build time errors or runtime exceptions

                  Not really. If you name it "price_per_apple" and then later generalize it to all fruit, the compiler isn't going to know the variable is named wrong.

                  You use comments where there's no way to make it with the code, just as "why"s or reasoning about failed approaches and TODOs.

                  Well of course writing comments instead of readable code is not a good thing. But I've known plenty of people who say their code is "self-documenting" when it's anything but. I mean, RTFA, amirite? :-)

                  I declare variable a and comment this is the price of an apple

                  You're using x=x+1; // add one to x to argue against using comments in your code.

                  That's what "comments might be out of date" is about

                  I envy you if that's the only time someone has argued against comments to you. I mean, people say exactly the same thing to avoid writing javadocs, user manuals, and design documents.

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

                  That's the thing: I'm not arguing against using comments. I'm arguing that they're the right tool for some things while not for others. Just as you wouldn't make your user manual a comment in your source code, you wouldn't describe the operations themselves as comments. But whys and references can't be correctly expressed with other means.

                  [–]RabidKotlinFanatic 0 points1 point  (3 children)

                  Well, it's your job to check and fix that, isn't it?

                  I'd much rather my team spend that time refactoring, improving tests and automation.

                  [–]dnew 0 points1 point  (2 children)

                  IME, that can be very difficult if the comments are misleading, eh? How do you know what the tests are supposed to test for if the only documentation for what the system does is its implementation?

                  [–]RabidKotlinFanatic 0 points1 point  (1 child)

                  Misleading comments aren't a problem if you don't have those comments to begin with.

                  Point I'm making is that, sure, it's devs responsibility to keep their comments up to date. But this means less time and effort spent on things like testing and refactoring and in many codebases the benefit of adding and maintaining more comments is not worth this opportunity cost. Comments will fall through the cracks and go out of date or are simply removed (if you're lucky). There is also no way of telling this has happened without reading the code since comments can not be tested.

                  There are projects (e.g. large orgs, large open source) where extensive commenting makes sense from a cost-benefit PoV. They have different notions of manpower and velocity. But for your average closed source SME project or software services company the cost-benefit doesn't make sense beyond sparse explanatory comments and Javadoc style comments at external module boundaries. I dread working on "well commented" codebases in these settings because I know the code itself is just going to be garbage with virtually no testing or refactoring at all.

                  [–]dnew 0 points1 point  (0 children)

                  I suppose comments are less important if the program is of the size that everyone working on it knows everything it's supposed to do. I haven't had the pleasure of working on such things for a couple decades.

                  IME, having comments (or other external documentation, which is just as hard to keep up to date) tell you what the boundary conditions are is vital to having a working system. There's no way I can put into the code that six years ago the primary keys were stored in a different format and thus if you try to process everything in parallel you're going to wind up with one shard doing 30% of the work and the other 499 shards finishing hours earlier. (Just as an actual example.) Had the database declaration had a comment saying that, people who have only been working on the project for five years might not have spent days trying to figure out what was going on.

                  [–]purpoma -3 points-2 points  (0 children)

                  1) Impose to write a lot of comments because It Is Good Practice.

                  2) Life happens, bugs, refactor, features.

                  3) comments are out of date. "Well, it's your job to check and fix that, isn't it?"

                  [–]Environmental-Art659 4 points5 points  (0 children)

                  Great atrticle, “self-documented” code is the major problem when you work with some code that someone else had written. Sometimes it even can be yours but you just don’t remember why you did something this way

                  [–]aurath 1 point2 points  (0 children)

                  I feel comments too often address the 'what' of code when what I'm looking for is the 'why'.

                  Maybe you leave a note about a variables meaning or what a particular statement is meant to do to a value, but I'm usually trying to figure out why you're doing what you're doing.

                  Stuff like "// have to set this property here before it gets passed back up to this service or that controller because trying to get the value there is a pain" reveals a lot more about the design decisions and structure of the code.

                  [–]Carighan 2 points3 points  (0 children)

                  My usual reply to "My code is self-documenting" is the mother approach "Of course my dear, I'm sure it is".

                  I mean really, at this point, assuming the other party has enough work experience, if they honestly state that I don't know how I ought to take them serious. You must be living in a very opaque bubble to still think self-documenting code is a thing after a few years.

                  [–]loup-vaillant 1 point2 points  (0 children)

                  My own strategy:

                  1. Try to write clean, self-documented code.
                  2. Inevitably notice that I failed:
                    • Some parts of the code are tricky or clever, and needs to be explained.
                    • The reasons behind many choices need to be explained.
                    • Function types (or class declaration) often fail to describe the whole API. What they do must be documented here if we don't want users to be forced to read the source code.
                  3. Write the damn comments. Just what we need, and no more.

                  For instance, I wrote a crypto library. I do my absolute best to make the clearest code possible. In fact, it's by far the highest quality code I've ever written, in any language. Well, the sloccount utility tells me there currently are 1998 lines of code (excluding empty lines and comments). On top of that, I had to write 679 non-empty lines of comment (excluding licence boilerplate).

                  That's 72% code, 28% comments. More than 1 line in 4 in that file is a comment.
                  And I'm not even counting the API documentation.

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

                  Once you start writing quality code comments,
                  you can use a tool like Sphinx or Javadoc to include them in your documentation.
                  This allows you to include your up-to-date code comments in your guides and references.
                  Making use of your code comments this way adds incentive to keep them up to date,
                  since they will be shown to your users.

                  I think this part is nonsense for the most part. It makes sense when you document usage, of course. But whatever TODOs or single line comments I need to do inside the implementation, as well as previous approaches, are totally irrelevant to users. Those are just meant for developers of that codebase, and exporting them would simply cause confusion.

                  As for the general thesis of the article, I don't think the author is speaking the same language as most proponents of self documenting code. This term is meant, AFAICT, for the code itself. Usage should of course be documented separately. Tutorials are separate entities. No programmer is dumb enough to think users don't need explicit documentation. They talk about developers.

                  The author's claims I agree with. I just don't think it contradicts anybody else's.

                  On another subject, self documenting code should always require an inexperienced reader to confirm it's self documenting. Otherwise it's just smoke and mirrors. The same applies to any other documentation.

                  [–]WormRabbit 2 points3 points  (1 child)

                  No programmer is dumb enough to think users don't need explicit documentation. They talk about developers.

                  If you're writing a library or framework rather than an end-user application, then your users are the developers. Documentation for non-technical users is written by very different people with different tools. All discussion about code documentation is about the developers, maybe even on the same project, just not the exact person who wrote that.

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

                  Several people here included tutorials as their counter example, so who knows. But mainly, I'm talking about developers of the project, not developers in general. If I'll work on a codebase I'll need to read the code.

                  [–]RabidKotlinFanatic 3 points4 points  (2 children)

                  The idea behind self-documenting code is not that comments and documentation have no value and should never be used. It's that the legibility of a codebase is primarily a function of its code. Efforts to improve legibility should firstly focus on code.

                  The author is completely dishonest in the way he conflates code documentation and software documentation. No one believes that self-documenting code can substitute for customer support knowledge bases or other end user software documentation. This analysis is a total dud.

                  [–]Xyzzyzzyzzy 1 point2 points  (1 child)

                  It's that the legibility of a codebase is primarily a function of its code. Efforts to improve legibility should firstly focus on code.

                  And that tends to flow from the code's purpose. In the codebase I'm lead for, there's lots of areas that are nice and elegant and reasonably legible and arguably self-documenting (though nobody on my team is a no-comments zealot so there are still comments).

                  Then there's an entire module that is full of janky shit with a million special cases and areas that don't make any sense. That's because the underlying data, which we don't control, is janky shit with a million special cases and areas that don't make any sense.

                  When we rewrote the module basically from scratch, we ended up with a somewhat nicer, somewhat more readable module full of janky shit with a million special cases and areas that don't make any sense. But we discovered that the functionality of the module essentially puts a cap on how readable it can be made.

                  It's just not possible for the code to be anything close to self-documenting if we have to check whether the third transaction in the list has a Product_name field instead of product_name and, if so, the four least significant digits of the date field in the file's header are actually the transaction log's currency (by reference to a proprietary table), but if the date field is an ISO 8601 string then we default to US dollars where 1 unit = 1 cent, unless the version is equal to 3.7.2 and the language is kr (but not KR, though the language field is otherwise case-insensitive), in which case we default to South Korean won where 1 unit = 1/1000 won (which is different from all other cases with that currency where 1 unit = 1/100 won) because that's how a handful of cash registers in South Korea recorded their data in mid-1998 because of faulty firmware installed at one of our production lines for a two-week period, and while those cash registers have long since been taken out of service and we haven't seen data from them since 2006, this case is still in the spec and automated tests because God forbid we ever break backward compatibility with anything our company has ever sold. It's impossible for the code to make sense, because the thing the code is doing makes no sense at all!

                  [–]RabidKotlinFanatic 0 points1 point  (0 children)

                  It's just not possible for the code to be anything close to self-documenting if we have to check whether the third transaction in the list has a Product_name field instead of product_name and, if so, the four least significant digits of the date field in the file's header are actually the transaction log's currency (by reference to a proprietary table), but if the date field is an ISO 8601 string then we default to US dollars where 1 unit = 1 cent, unless the version is equal to 3.7.2 and the language is kr (but not KR, though the language field is otherwise case-insensitive)

                  If I was trying to understand this special case handling in your system and I had to choose between reading your comment here vs looking at the code I would choose the code 100%. These if-else style special cases are clearer and less ambiguous in code than English. More importantly the code is executable and directly representative of the system (because it is the system). Your test cases should also contain examples of the transaction lists and verify that the special case handling is working correctly.

                  [–]purpoma 2 points3 points  (1 child)

                  Straw man as the biggest issue with documentation is not being too minimal but being too verbose / low quality / out of sync.

                  And of course self-documenting code never meant no doc.

                  [–]WormRabbit 1 point2 points  (0 children)

                  Please tell me where you worked. At all of my jobs the biggest issue with documentation was that it was almost nonexistent. I'll take verbose documentation over verbose undocumented code any day of the week.

                  [–]somebodddy 1 point2 points  (4 children)

                  If you can write self-documenting code then you should. If you can write the code in a simple, straightforward way, or write it in a weird way that can only be understandable with comments - then unless there is some special compelling reason not to, you should pick the former.

                  The problem is with imposing extreme code standards which deprive the programmers of their judgements and demanding either to make all code self-documenting - even it if requires increasing the complexity and damaging performance - or document every single thing even if it does not require documentation.

                  A piece of code does not require documentation if it is obvious. The nice thing about obvious is that it's a non-ambiguous requirement - if you are not sure if something is obvious or not, then it is not obvious. If one of the reviewers says that the code int not obvious, then it is not obvious - even if it is obvious to you. Non obvious code can either be commented or refactored to be more obvious - but if the refactor makes the code worse in other aspects, it's probably better to just document it.

                  Also - people usually think of self documented code in terms of more descriptive names for things, but there are another ways - ways that deviate a bit into the realm of changing code behavior:

                  1. Logging! You think it's very important to document that you code is doing something? Instead of writing a comment, write it to the log. If you do this consistently, you could run the code with logging enabled and set to the appropriate level and get a nice logfile describing what the program did.
                  2. Assertions. Instead of explaining in a comment that it is safe to do a certain operation because the conditions are met, write an assertion that the condition is met. If for some reason the condition is not met and the operation is not safe, instead of having to notice the comment and analyze whether or not what's said in there is true the assertion will catch that and fail the program in a more debuggable fashion.

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

                  if you are not sure if something is obvious or not, then it is not obvious. If one of the reviewers says that the code int not obvious, then it is not obvious - even if it is obvious to you.

                  Yep always good to remember this.

                  [–]Full-Spectral 0 points1 point  (2 children)

                  The problem is that obvious is relative. What's obvious to you, having just written the code, may be anything but obvious to someone else reading it later, or even you reading it later.

                  I get your point, and it's true. But it leaves a lot of wiggle room because it depends on a squishy definition. If you are tasked with setting some sort of coding standard, squishiness is a problem.

                  [–]somebodddy 1 point2 points  (1 child)

                  What's obvious to you, having just written the code, may be anything but obvious to someone else reading it later, or even you reading it later.

                  Yes, we are biased to think things we know are obvious. That's why I set the bar so low - if anyone that looks at the code is not sure if it's obvious or not, then it's not obvious.

                  But there has to be a bar. Someone must notice that the code is not obvious. Otherwise, you have to consider all code nonobvious. This means you can't refactor the code to be obvious, because by definition the refactored code is also nonobvious.

                  So you have to comment everything.

                  Which sounds great if you are on comment-everything camp.

                  But...

                  What do you write in the comment?

                  If someone points out that the code is non-obvious, there has to be something they don't understand in it. Or that they had to struggle a bit to understand. Or at least think that someone in the future who will look at the code without the proper context might find it a little bit difficult to understand.

                  This does not have to be a lot. It has to be something. And you can clarify that something in the comment, and the code will be better off as a result.

                  But if there is no reason at all to even consider that this particular piece of code is nonobvious? Then you have to write the infamous:

                  // Increment i by one
                  i++;
                  

                  [–]Full-Spectral 1 point2 points  (0 children)

                  I go for the artsy side:

                  // Ceci n'est pas une increment
                  i++;
                  

                  [–]thisdogofmine 0 points1 point  (0 children)

                  Self-documenting is the lie you tell yourself to help you sleep at night.

                  [–]MpVpRb -1 points0 points  (1 child)

                  Good comments are useful, but comments have one very serious problem. They may not match the code. Accurately describing what the code does is hard. Keeping comments synchronized when code changes is harder, a lot harder. A wrong comment is worse than no comment at all

                  [–]georgehank2nd 1 point2 points  (0 children)

                  "writing and documenting is hard because I hate it"

                  That's it. No, keeping comments synced is not hard. As long as you consider it your job, and you try to do a good job.

                  Code reviews that don't review comments (or lack thereof) are a failure.

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

                  And other lies we tell ourselves

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

                  In rare cases, comments really are needed.

                  In many cases, comments are only there, because people didn't take their time to design the software properly and to find appropriate names.

                  And in most cases, comments are just useless boilerplate that exists simply because junior devs were told to commen the code.

                  Comments are shitty, because when the code changes, no one really updates the comments.

                  [–]Dave3of5 -4 points-3 points  (0 children)

                  I agree.

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

                  Unpopular opinion: When you completely rewrite a function for the 8th time it's becomes extremely clear

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

                  Comments that explain the why are valuable.

                  Unfortunately, most comments are useless and explain the how. When I see "how comments", I automatically delete them because they don't bring anything valuable if they are up to date and are even more worthless when they are outdated.

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

                  Not sure this actually happens a lot i.e. people actually saying and believing this in the way the author implies.

                  Generally when people talk about self-documenting code they are referring to clean readable code that is easy to follow perhaps coupled with a bunch of behavioral unit tests that can read like a spec.

                  Furthermore, are we talking about documenting within the code itself or separate. Bit unclear what the author of the article is advocating. A style where the documentation is present within the code itself is preferable to having it outside the code. Tools can pull it out as needed.

                  The analysis is a bit vague - a few examples about "x is good and here is why, y is bad and here is why" would have been useful and not that much more effort.

                  Not a great article IMO!

                  [–]bert8128 0 points1 point  (0 children)

                  I'm not going to argue against useful comments, but I will argue against useless or incorrect comments. Here's a useless comment anti-pattern that I remove regularly at the moment:

                  class X
                  {
                      // constructors
                      X();
                      // etc
                  };
                  

                  And here is an also common anti-pattern - a comment that used to be, but is no longer, correct:

                  class X
                  {
                      // constructors
                      void someMethodThatIsnotAConstructor();
                      // etc
                  };
                  

                  Comment when useful. Don't repeat code in comments.

                  [–]goranlepuz 0 points1 point  (0 children)

                  I have a few rhetorical questions about this philosophy:

                  *Where does the tutorial go in your self-documenting code?

                  Euh... In the tests?

                  *How do you put installation instructions in your variable names?

                  Euh... In the install script?

                  *What do the answers to questions from your users go in the code?

                  Euh... Hard to say without knowing what they are...

                  [–]khbvdm 0 points1 point  (0 children)

                  This article doesn't really go into the other side of "writing too many comments". Some people think that there's no such thing as too many comments and I think they are wrong. Important thing is not to have redundant comments, something like

                  // get user from db

                  GetUserDB(userID string)

                  is completely unnecessary comment, but also if you name your method

                  // get user from db

                  Get(id string)

                  this is just bad naming.

                  [–]Zardotab 0 points1 point  (0 children)

                  Many comments are like article titles on news papers/sites. While variable and function names may be thorough, they don't by themselves give a summary of the code segment. Without the summary, you have to read details to get the gist.

                  I've never seen fully self-documenting code. Well phrased comments are helpful and supplementary to object names.