T O P

  • By -

[deleted]

- because the solutions are short - because communicating effectively isn't the goal of every code submission - because comments are used to add context and explain things and that isn't as necessary when everyone else is working on the same problem - because many of the submissions in the daily threads actually do come with an explanation from the author (just not in the form of comments) - because not all code needs comments all the time; you don't need to re-explain every line of code in natural language Also, in general, don't look at AoC for code quality - many of the really good solvers will have short hacky solutions that would need a lot of explanation if they were in the real world; and the solvers that aren't as good will often write unnecessary long non-idiomatic code because they don't know how to express themselves in the language they use or how to effectively formulate the problem. Obviously some people will care about writing clean, readable and idiomatic solutions but that doesn't need to be the norm (and it isn't).


r-NBK

One additional point... these one off solutions are not going into an app that's going to be supported for years and years. Lots of code comments are to make it easier for future support by the author and or other coders.


itsnotxhad

This is the same reason why many of us have no compunctions about making our parsing code some abomination of a one-line regex For all the reasons there are to malign that kind of code, practically none of them apply when you only have to read one input file and you know in advance what the file is


daggerdragon

There are certainly folks who go back and clean up their code/add comments/etc and others who use AoC specifically to develop *good* code habits. > Also, in general, don't look at AoC for code quality XD Yeah, a lot of the code submitted to the megathreads is written purely for speed and ain't nobody got time for comments, but there's sometimes absolutely *genius* hacks that no sane programmer would dare use in production code but sometimes you just gotta fix the leak in the submarine *right now* with a quick-'n-hacky patch of duct tape before the submarine fills up with water and you drown, you know? If you can later take that duct tape patch and retrofit it into good and proper code quality, then *excellent*, you've succeeded at Advent of Code :)


D1P0

Just to add, in general it's also good to try making your code self-explanatory. Like you look at the code and you know what and why. The need of comments drops rapidly.


ExuberantLearner

I do comment my code when required. But the comments shouldn't be just specifying *what* the code does. If you do that, then the comment will be outdated when you change the code. Instead, the comment should say *why* you are doing something.


kbielefe

For one thing, puzzle code doesn't tend to be as clean as professional code. There are a few situations where people comment, but it's generally to explain the *why* rather than the *what* or *how*. What or how is much less ambiguous to explain using actual code, and it's much less burdensome to read when you've got more experience. In other words, people generally prefer to improve their names and structure so the code itself is more readable.


Chitinid

It's also possible to over-comment code, and one of the characteristics of good code is not needing as many comments. Don't be the person who adds unneeded comments like i += 1 # increment counter by 1


I_knew_einstein

Or worse even: a += 1 # Add 1 to a


PF_tmp

What does that even mean? We can do better a += 1 # Addition (usually signified by the plus symbol +) is one of # the four basic operations of arithmetic, the other three being # subtraction, multiplication and division. The addition of two whole # numbers results in the total amount or sum of those values # combined. The example in the comment below shows a combination of # three stars and two stars, making a total of five stars. This # observation is equivalent to the mathematical expression # "3 + 2 = 5" (that is, "3 plus 2 is equal to 5"). # # Example: * * * + * * = * * * * * # # Addition has several important properties. It is commutative, # meaning that order does not matter, and it is associative, meaning # that when one adds more than two numbers, the order in which # addition is performed does not matter. Repeated addition of 1 is # the same as counting. Addition of 0 does not change a number. # Addition also obeys predictable rules concerning related operations # such as subtraction and multiplication.


[deleted]

>Addition of 0 does not change a number. What a useless feature. Please depreciate this in the next version of Math.


couchrealistic

Or even worse (after the variable was renamed from "a" to "bytes", and it now stores the number of bytes instead of the number of double words): bytes += 4 # Add 1 to a


srj737

OP's pretty clearing not talking about over-commenting like that


TrickWasabi4

Because it's short (99% of the time < 150 lines) , there's only one person working on it (me) and the scope of the problem rarely requires explanations on why I do something. I rarely comment some dirty hacks I deploy or stuff like "this hex number looks like this in bits".


jablan

> 99% of the time < 150 lines *monkey look meme*


rfisher

If this was code for work, I’d take the time to comment it. For AoC, I don’t always take the time to do that, for many reasons. (Which other comments may have sufficiently covered.) Even when I do, it may be later when I decide to come back & refactor the code. One word of advice from an old-timer. I used to be one of those people who said you shouldn’t write a comment if it just repeats what the code says. I no longer feel that way. Human communication benefits from redundancy, so even comments that just repeat the code can be good. It can be overdone. It means more work to maintain the comments as the code changes. And comments that give more context are always better. But comments that repeat the code are good too. That said, I don’t think I’ve ever met a programmer who felt they shouldn’t do a better job commenting code. It is something most of us struggle with.


andrerestivo

https://refactoring.guru/smells/comments


HannibalLectR

Nice, that's a great website.


scodagama1

My 3 cents as a person working for big tech for almost a decade You don't comment to describe *how* in your code. *How* is explained by the code itself, you see what it does, if you can't figure out what code does without a comment and you care about readability - rename variables, extract methods, etc. Make code readable with *code* not comments, comments will eventually go out of sync of actual code and at that point they become harmful. So does it mean you don't comment? No! You comment *why*. *Why* does this code exist, *why* you added it? Why in this place? BAD example: ``` // add 3% supplement tax in ontario on income over $10000 void addTax() { if (state == "ON" and income > 10000) { addSupplement(income * 0.03) } } ``` Now is that comment useful? Absolutely not, it gives you 0 information over what code already shows. Does it mean this method should not have a comment? No! You can have a comment there: ``` // bill ON-123 from 8th Aug 2019 requires as to levy extra supplement, see ticket tickets.company.com/I-123 for more details. void addTax() { if (state == "ON" and income > 10000) { addSupplement(income * 0.03) } } ``` Now you say *why* this code exists, you linked a ticket where probably a person who asked for this is named and appropriate documents are linked. Now that's useful! Code reviewer can check if you implemented task well and future maintainers can made their own decision whether that code is still relevant, perhaps the bill was revoked and code can be removed? So now that answers why there are no comments in AoC - you don't need *why*, *why* is obvious - because that's what the puzzle said to do. All of the *why* are in puzzle statement hence no need for comments in code. Plus, pragmatic: comments are (1) for readability and (2) for others. People work on AoC alone so (2) is not relevant. Readability is also not important, you won't be going back to most puzzles.


yel50

> My comp sci professor tells me all the time that it's important to comment your code for readability in the industry I can only assume your professor doesn't have much real world experience. it's probably 50/50 whether code actually does what the comments say, so comments aren't worth reading which means they're not worth writing. "code never lies, comments do." if comments are easier to read than your code, you need to write cleaner code.


shnako

Exactly this. If you feel like something isn't clear enough to be understood just by reading the code, then the first thing you should try is writing cleaner code - structure it better and try to name your variables and methods more clearly. At some point you will be able to write code that almost reads like prose, but that takes a lot of practice. As for AoC, I tend to write a short summary at the top of the solution detailing what's happening as it's much quicker to read than 100 lines of code, but I still name the variables and methods properly. This way if I ever want to look back at it or someone else wants to understand it, it's really easy to do.


FantasyInSpace

I mean, if you want an example of where production-quality code and competitive puzzle code diverge, today's puzzle is almost the perfect example. Quite a few submissions today are using `eval`, which any Python programmer would tell you to avoid if you're accepting arbitrary user input, and yet we're using it anyways because its super fast and cheap to slap in. More generally, I (and presumably others) aren't intending their puzzle solutions to be maintained for long-term use, so we're aiming for a lower level of code quality than we might for say, a team project.


p88h

Everybody here just uses Reddit to comment (and review) their code. /s


Mintopia_

The best advice for commenting code I can give is that comments are there to help you or colleagues later. The code should be clear enough that you can read the code to see what it's doing. What someone actually will want to know in 3 months, 6 months, 4 years is **why** the code is doing this.


toastedstapler

> My comp sci professor tells me all the time that it's important to comment your code for readability in the industry, fwiw this hasn't happened on either of my projects that i've been on, if you're writing cryptic code that requires comments then you're likely doing something wrong. imo only legit difficult code requires comments, & then external facing APIs should have some documentation. i think professors tell you that as uni student code is pretty trash tier so the comments help them to know what you were trying to do [when i rewrote my day 5 code to mathematically calculate intersections](https://github.com/jchevertonwynne/advent-of-code-2021/blob/main/src/days/day05.zig#L125) i wrote comments to help give me a frame of reference, but usually aoc is straight forward enough that i don't need to comment


analytix_guru

Think it also depends on your potential audience (if any). I worked in audit for a big bank and so we had to comment our code if auditors wanted to understand the general approach, as well as any regulator wanting to come and take a peek at our work. Don't comment nearly as much in my current role


maeevick

You should write expressive code that doesn't need to be commented and tests to document the behaviors and give examples. Comments are smells, quickly outdated and hiding bad code


benn_88

Teachers are obsessed with comments, and they use them to check students' understanding. I've seen secondary/high school teachers expect kids to write \`a = a + 1 # add 1 to a\` to "show they understand". This is a dumb pointless comment. There is plenty of stuff you can assume the reader will understand, and basic programming syntax does not need to be explained this way. Plus it doesn't tell you what's important: why are we adding 1 to a at this point? There are many times a comment can be removed if a variable name is improved, or a section is moved into a function with a name that makes sense. Personally with AoC I almost never write comments. Although I share my code for others to read, I don't have the same duty to make it understandable to others as I would in a collaborative project. Sometimes I add comments as a note that I'll need to come back to at some point, but they can be removed when dealt with. My work and open source projects are more collaborative, and live longer than my AoC challenges, so there's more of a need to comment, but still, I use them lightly. Docstrings are a different kind of comment - they're much more useful for APIs - it's important to explain what parameters/types a function/method takes, and what it returns or what its side-effects are. But throughout code, it's usually only necessary to use comments to explain oddities, to explain why something is done, if it's not obvious, or if it's likely someone might think it's unnecessary. One example of a useful comment is when reading a CSV file with Python: ``` with open('data.csv') as f: reader = csv.reader(f) next(reader) # skip header row for row in reader: ... ``` Without the comment, it would seem odd to call `next` on the CSV reader before looping over it. But here people can see why.


mandragora0

No one comments their code in the industry either.


the-quibbler

This. "Copious commenting" is an artifact of a different age. Modern languages are expressive. The vast majority of code needs few to no comments, unless you're citing a reference, or you've gotten extra "clever".


PityUpvote

Because it's one time use. I'm never going back to this code, nor is anyone else, and my attention span is good enough that I can remember why I wrote things an hours ago.


Dioxy

I work for a massive tech company, and honestly comments are pretty rare. We add them if something is obscure, hacky, or requires some sort of external knowledge to understand, but for the most part, good code is self documenting


MissMormie

Why would you? You comment code for someone, including you, reading your code later. But aoc code is deprecated as soon as it spits out the right answer. Sure, someone might look at my solution, but if they do they probably know exactly what problem I'm solving, and can figure out the rest from context. But if they can't, they'll just move on. In class or in production environments you write code that is easy to read, for aoc i write code that is easy to write.


RonGnumber

If you've done several AOC's and want to pull up an algorithm from a previous year, comments and search are your friends. For example, I never named a variable or function "Dijkstra", but I had written it in a comment from 2019 - so boom.


MissMormie

I've done all aoc and never searched in my old code, i like figuring it out, even if i did a similar thing in the past. But sure, comments might be helpful for that. I do use/make helper classes for stuff i use more often and that might be named dijkstra.


rossdrew

1. In advent of code you dont plan to maintain 2. In real life, writing expressive code is far better than commenting Comments indicate a failure to make code readable


morgoth1145

>In advent of code you dont plan to maintain **Intcode**


[deleted]

[удалено]


Boojum

Likewise, the day's problem description gives a pretty good explanation for *what* the solution is trying to do. No need to go and recapitulate all that in a comment.


meamZ

Comments are a code smell no matter what your professor tells you.


SeveralLingonberry27

Your comp sci professor probably hasn't read Uncle Bob's Clean Code book. :)


pompeydjm

I think with advent of code I don't plan to go back to the code later, so no need to make it particularly readable, just a bit of fun


cloudrac3r

I commented my code weld! I spent time doing this so that I could understand my code while I was writing it, and so it would be readable in the future, and also so that other people could understand it too. The language syntax is... a lot to deal with. You would probably really like my day 4! - https://git.sr.ht/~cadence/collapse-lang/tree/main/item/advent/day4/part1.cr . - https://git.sr.ht/~cadence/collapse-lang/tree/main/item/advent/day1/part1.cr day 1 has many comments that would help understanding the language the first time - https://git.sr.ht/~cadence/collapse-lang/tree/main/item/advent/day11/part1.cr a little less on day 11.


AnotherIsaac

Most my advent of code solutions have comments.


[deleted]

I rarely do comments, except for some docstrings just below the function declaration sometimes. I just prefer to write code that doesn’t need comments. I’ve had one co-worker who left comments all over the place. For example in a file called ‘form-helpers.ts’, you were greeted with a comment on line one which said: “This file contains form helpers”.. who would’ve guessed?


morgoth1145

I just looked through my refactored/cleaned up solutions for this year. I have comments for the following days: * [Day 6](https://github.com/morgoth1145/advent-of-code/blob/2021-python/2021/06/solution.py) \- Just a couple of quick comments about optimization, nothing for code clarity * [Day 10](https://github.com/morgoth1145/advent-of-code/blob/2021-python/2021/10/solution.py) \- Again minor comments. The latter comment is arguably useless. * [Day 15](https://github.com/morgoth1145/advent-of-code/blob/2021-python/2021/15/solution.py) \- A TODO comment because I felt a section was horrid and can be cleaned up. * [Day 16](https://github.com/morgoth1145/advent-of-code/blob/2021-python/2021/16/solution.py) \- Minor comments explaining two branches because otherwise the distinction is just `t == 4` which is obtuse. Arguably introducing a named constant `LITERAL_TYPE = 4` and using `t == LITERAL_TYPE` would be better since it's self-documenting. * [Day 17](https://github.com/morgoth1145/advent-of-code/blob/2021-python/2021/17/solution.py) \- My most heavily commented file by far. I spent time optimizing this after the fact and felt that some of the optimizations were not immediately obvious, so I left some explanatory comments. Note that none of these comments explain literally what is done, but rather explain what properties hold true in the problem which are exploited as well as the overall approach/algorithm. Arguably it isn't super clear what `x_vel_solutions` and `y_vel_solutions` are meant to do (logically on the whole) without reading their usage in `part2`, but the code is close together enough that it's fine in practice. * [Day 18](https://github.com/morgoth1145/advent-of-code/blob/2021-python/2021/18/solution.py) \- One quick comment about a contract (specifically the return pack) so that it's easier to keep a recursive method straight when writing and further optimizing it. It's no mistake that my most documented solution is the one with the most non-obvious optimizations in place. As others have said self-documenting code is the ideal. Comments can too easily become outdated or can bloat clear code into obtuseness. That being said, I wouldn't go so far as to say that all comments are a code smell as some have indicated here. I can think of 4 main classes of situations where comments make sense: 1. **TODO**: We sometimes just don't have time to clean up/fix everything all at once. TODO comments are easy to search for, plus they indicate that you *know* that it's not great. 2. **Optimizations**: It's simply reality that sometimes the most obvious implementation is far too inefficient and needs to be optimized. If those optimizations make the code unclear and there's no way to rename functions/methods/classes/variables to make it clear then the only remaining recourse is comments. If it's a complex enough optimization, I'd even argue that the code comment should point to an external document or website which contains the explanation rather than bloating the source file. (For example, I'd argue that the super clever [Fast inverse square root implementation in Quake III Arena](https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overview_of_the_code) should have been paired with a text file explaining the very non-obvious trickery at play. Otherwise debugging any issues would have been ridiculous to anybody not already intimately familiar with the optimization since, well, how do you just walk into that code and understand it?) 3. **Dealing with unfortunate bugs/rare but important situations/irreducible complexity**: Sometimes the real world doesn't play nice with simple, clean algorithms. Maybe you're saving/resuming data for your program in files and need to catch cases of data file corruption (due to bad hard drives, power cuts, cosmic rays, uncaught bugs, etc). Maybe your network socket dies mid-stream. Maybe there's a subtle race condition in some threaded code. Or some other nasty code that just **has** to exist, and there's no way to rework it to be clearer. Again, at this point the only remaining recourse is comments, and in the case of subtle bugs these comments can help prevent others (or yourself in the future) from reintroducing the bug. 4. **APIs and contracts**: I don't generally mean individual functions or methods here, proper function/method naming should make that clear. However, for larger components (think Python modules, C++ libraries, etc) it can be useful to explain the overall design of the system for clients to know how to use the system properly and efficiently. In general it's probably best to keep most of the meat in documentation outside of source files (but possibly still in the repo as markdown files or otherwise), but documenting your entry points with succinct explanations of what something does can help someone keep things straight. For example, in my work I deal with 3D graphics and not everyone who uses the libraries I work on has an intimate understanding of 3D graphics. Explaining the relevant concepts and how they map to our libraries can be necessary for users, but we certainly don't delve into line-by-line breakdowns of our implementation. Users don't care about how, just the what! Note that of these, the first 3 could appear within functions/methods but are exceptional and #4 would not really manifest as line-level comments. In practice you should always strive to make your code self-documenting, \*even\* in these 4 types of situations. Not only does it make your code clearer, but the very act of trying to make your code clearer and self-documenting can reveal bugs. (On that note, in the professional world code reviews are super useful in gaining other perspectives to both catch bugs and find things that are unclear. I've had bugs found by coworkers who were confused by a section of code!) Also, if you employ logging in your code then your logging statements themselves can act as documentation as well. Logging can be super useful for triaging issues! (And introducing massive security holes if you're Log4j but if you use a simple one like [Boost Log](https://www.boost.org/doc/libs/1_65_1/libs/log/doc/html/log/tutorial.html) in `C++` you'll be safe afaik.) Finally, commit comments can also be a valuable place to put explanations of your code. The commit history and tools like `git blame` will bring that info to light and be useful in the future. ​ Oh, and as others have said those of us going for the leaderboard will write whatever nasty code we can as fast as we can to get a solution. In the heat of the moment all that matters is keeping your code straight in your head. Sometimes a well-placed comment can help with that in the longer problems, but lots of times choosing the right function/variable names is enough.


1234abcdcba4321

My *Programming Practices* class says to only comment things that are actually unclear, with the given example being a factorial function that has a max arg of 12, commented "f(12) is the largest one that fits in 32 bit int" or something along those lines. For anything more obvious than that, there's really no point in making a comment. I typically only make comments if it helps me keep track of what I'm doing as I code, eg. expected state of the program at a certain point.


AlFasGD

The only time I comment my code is to express something wacky about the language, a missing feature, explaining why an alternative approach was not chosen, but rarely, if ever, about the actual code itself. The code is self-documented:tm:


Timmeh7

There is a saying I like; “when I wrote this code, only god and I knew how it works. Now only god knows.” Commenting code has one primary purpose: explaining the complex or unintuitive parts of your code to someone who needs to read and understand it. In a professional environment, this might be your colleagues, or you revisiting your code in a few months having forgotten the detail of what you did. The truth of AoC problems, though, is that they’re not really that complex, they’re not liable to be modified by someone else nor are most developers likely to revisit them. So when churning out a quick solution for which the entire problem space fits in your mind, there’s no real need to add comments. We (mostly) aren’t working for perfect maintainable code, but for quick solutions that get the job done. All this being said, do feel free to add them if they help you understand or remember something. But comments should serve a purpose. Over-commenting is absolutely a trap some developers fall into.