I find it puzzling that “this still happens now that we have Git.”
I guess people may have “an uneasy feeling about losing that code fragment, considered more sane or stable, in some years old commit.”
I believe that “source code is not for making backups.”
My recommended alternative is: “Either make sure the new function is better than the past one, or take it just in your development tree until you are sure.”
I define backup comments as comments preserving older versions of code blocks or whole functions when a developer feels insecure about a change: “Finally backup comments are the ones where the developer comments older versions of some code block or even a whole function, because she or he is insecure about the change that was operated in the new one.”
I consider a change that still needs its old implementation saved unfinished: “If you want to save an older version of a function or code part, your work is not finished and cannot be committed.”
I see comments as “Comments are rubber duck debugging on steroids, except you are not talking with a rubber duck, but with the future reader of the code,” and use the act of writing them to examine whether what I am stating is acceptable, honorable, and good enough.
When an explanation does not seem decent enough, I do more work and improve it: “if it is not, you make your homework, and come up with something more decent.”
I treat comment-writing as similar to documentation: “the writer attempts to provide the gist of what a given piece of code does, what are the guarantees, the side effects.”
Trying to explain code can expose missing pieces: “It is very easy while describing something to find that it has holes”
I consider behavior that cannot be explained because it emerges unpredictably from complexity a problem: “You can't really describe it all because you are not sure about a given behavior: such behavior is just emerging from complexity, at random.”
When comment-writing reveals that kind of unclear behavior, I go back and fix it: “You really don't want that, so you go back and fix it all.”
I consider uncovering unclear behavior and fixing it “a splendid reason to write comments.”
I reject the idea that writing comments is lesser work simply because one can code: “You may think that writing comments is a lesser noble form of work.”
I describe code as “a set of statement and function calls, or whatever your programming paradigm is.”
I note that code statements may not make much sense when the code itself is poor: “Sometimes such statements do not make much sense, honestly, if the code is not good.”
I say that writing good comments requires developing writing skills: “in order to write good comments, you have to develop your writing skills.”
I consider comment-writing useful for finding bugs: “This is often a bug hunting opportunity.”
I believe that “Comments require always to have some design process ongoing, and to understand the code you are writing in a deeper sense.”
I value comment-writing for the writing skills it develops: “The same writing skills will assist you writing emails, documentation, design documents, blog posts, and commit messages.”
I explain my motivation this way: “I write code because I have an urgent sense to share and communicate more than anything else.” I love writing comments as much as writing code itself.
I thanked Michel Martens for his feedback: “Thanks to Michel Martens for giving feedbacks during the writing of this blog post”.
I use guide comments to assist the reader through source code by providing clear division, rhythm, and introducing what comes next.
I believe guide comments’ sole reason to exist is to lower the cognitive load of the programmer reading some code.
The guide comment before unlinkClient(c) summarizes that it will close the socket, remove the I/O handlers, and remove references of the client from different places where active clients may be referenced.
I find that guide comments clearly divide the code in isolated sections, an addition to the code is very likely to be inserted in the appropriate section, instead of ending in some random part.
Redis is literally full of guide comments; basically every file you open will contain plenty of them.
I don't value code without such comments as less good, yet I firmly believe that if people regard the Redis code as readable, some part of the reason is because of all the guide comments.
I define a trivial comment as a guide comment where the cognitive load of reading the comment is the same or higher than just reading the associated code.
I use guide comments extensively, while recognizing their value is subjective and that readers may or may not like them. In the rax.c example, they signpost the node-callback operation and what happens when the next step finds a key; they add nothing to the code’s meaning, but help readers follow it and confirm their understanding. In networking.c, section labels guide readers through replica-disconnection cleanup, and the comment before unlinkClient(c) gives the big picture without requiring a jump into the function. I recommend avoiding comments that merely restate an obvious operation, such as array_len++; /* Increment the length of our array. */.
I note that language limitations, design issues, or the natural complexity arising in systems can make it impossible to centralize a concept or interface in one place.
In a perfect world, checklist comments should never be needed, but in practice sometimes there are no escapes from that.
I use defensive comments to remind developers that touching one code section may require modifying other parts of the code.
Checklist comments are very common inside the Linux kernel, where the order of certain operations is extremely important.
I describe a checklist comment as doing one or both of these things: It tells you a set of actions to do when something is modified; it warns you about the way certain changes should be operated.
When adding a type ID, the checklist says to modify getTypeNameByID() as well.
When implementing a new blocking type, the checklist says to modify unblockClient() and replyToBlockedClientTimedOut().
If a blocking operation waits for certain keys to change state, the checklist says the clusterRedirectBlockedClientIfNeeded() function should also be updated.
I distinguish checklist comments from why comments: the why comment may tell you why a statement is there, the checklist comment used in the same case is more biased towards telling you what rules to follow if you want to modify it.
The served-slots update MUST happen after we update the master/replica state so that CLUSTER_NODE_MASTER flag will be set.
The Redis object structure uses the field widths type:4; encoding:4.
The Redis object’s lru field represents LRU time relative to global lru_clock, or LFU data: least significant 8 bits frequency and most significant 16 bits access time.
Redis uses 4 bits instead of 64 to represent the type.
I define teacher comments as comments that teach the domain in which the code operates, rather than explain the code itself or its side effects.
The LOLWUT command in version 5 needs to display rotated squares on the screen.
The LOLWUT teacher comment uses the parametric equations x = sin(k) and y = cos(k), which describe a circle for values going from 0 to 2*PI.
The square’s first point uses k = PI/4; the other three points come from incrementing K by PI/2 (90 degrees). To rotate it, the comment starts with k = PI/4 + rotation_angle.
The vanilla equations describe the square inside a circle of radius 1; drawing larger squares requires multiplying the obtained coordinates and then translating them.
For LOLWUT, this approach is simpler than implementing the abstract concept of 2D shape and then performing rotation/translation transformation.
I think teacher comments are of huge value: “They teach something in case the reader is not aware of such concepts, or at least provide a starting point for further investigation.”
I say that writing code that can be read by many programmers is a major goal of mine; developers without math skills can contribute some wonderful fix or optimization.
I believe code should be read other than being executed, since it is written by humans for other humans.
In the Redis radix-tree implementation, the comments re-state the whole data structure theory as it is implemented, showing the different cases and what the algorithm does to merge or split nodes; code follows each comment section.
After months of not touching the file implementing the radix tree, I was able to open it, fix a bug in a few minutes, and continue doing something else without studying again how a radix tree works.
The compressed node containing ANNIBALE represents A -> N -> N -> I -> B -> A -> L -> E, with its only child pointer pointing at the E node; characters are at the edges of the graph, not inside the nodes.
The radix-tree example also shows the compressed-node path "ANNIBALE" -> "SCO" -> [].
In split case 3a, when $SPLITPOS == 0, replace the old node with the split node, copy auxiliary data if any, fix the parent’s reference, and eventually free the old node while retaining its data for subsequent algorithm steps.
In split case 3b, when $SPLITPOS != 0, trim and reallocate the compressed node to contain $splitpos characters, link its child pointer to the split node, set iscompr to 0 if the new compressed-node length is 1, and fix the parent’s reference.
The code branch uses if (j == 0) for case 3a and the other branch for case 3b; it copies data when h->iskey, updates parentlink, and in the trimming branch sets trimmed->iscompr = j > 1 ? 1 : 0.
I say this level of commenting is not needed for everything: radix trees have many little details and corner cases that are hard to recall, and some details are specific to a given implementation. Doing this for a linked list does not make much sense; deciding when it is worthwhile is a matter of personal sensibility.
These examples show two uses of teacher comments: making a mathematical idea accessible in a small drawing routine, and keeping the theory and implementation details of a complex data structure together for future readers. The full radix-tree implementation is available at https://github.com/antirez/redis/blob/unstable/src/rax.c.
Redis streams allow to delete elements from the middle using the XDEL command; privacy regulations may prohibit retaining certain data. This is an unusual use case for a mostly append-only data structure.
If users delete more than 50% of items in the middle, the stream starts to fragment into “macro nodes.” Entries are flagged as deleted and are only reclaimed once all the entries in a given macro node are freed, so mass deletions change Streams’ memory behavior.
The GC TODO is guarded by this trigger condition: `entries + marked_deleted > 10 && marked_deleted > entries/2`. Before the check, the code subtracts `to_delete` from `entries` and adds it to `marked_deleted`.
I don't expect users to delete most history in a stream. For now, that makes garbage collection look like a non-issue, though I may introduce it in the future.
For possible future collection, the macro node could be compacted once the ratio between the deleted entries and the existing entries reach a given level; nearby nodes may be glued together after garbage collection.
I was afraid that later I would no longer remember what were the entry points to do the garbage collection, so I put TODO comments, and even wrote the trigger condition. I say this approach is probably not great.
I think a better approach would be to write, in the design comment at the top of the file, why we are currently not performing GC and what are the entry points for GC, if we want to add it later.
I describe FIXME, TODO, XXX, and “This is a hack” as forms of debt comments. They are not great in general, I try to avoid them, but it's not always possible, and sometimes instead of forgetting forever about a problem, I prefer to put a node inside the source code.
I recommend that one periodically grep for such comments, and see if it is possible to put the notes in a better place, or if the problem is no longer relevant or could be fixed right away.
Why comments explain the reason why the code is doing something, even if what the code is doing is crystal clear.
When we free the backlog, we always use a new replication ID and clear the ID2. Redis changes the replication ID, clears the secondary ID, and then frees the backlog.
The inconsistency scenario begins: Our replica is promoted to master. It's repl-id-2 will be the same as our repl-id. If the former master later receives writes without advancing its offset and then reconnects, the new master may accept its PSYNC request despite the divergent data.
When there is no backlog, the master_repl_offset is not updated.
As the former master, we receive updates that will not increment the master_repl_offset.
The new master may accept our PSYNC request by second replication ID, but there will be data inconsistency because we received writes.
The backlog is freed after the timeout condition if (idle > server.repl_backlog_time_limit) {; the log says: "Replication backlog freed after %d seconds ".
SYNC cannot be issued when the server has pending data to send to the client about already issued commands.
The replication-handshake output buffer may be duplicated to serve other replicas connecting while the RDB file for the first replica’s full sync is being created.
The pending-output check returns the error "SYNC and PSYNC are invalid with pending output".
The expiration loop condition is j < dbs_per_call && timelimit_exit == 0.
The selected database is server.db+(current_db % server.dbnum).
Processing different databases while time remains helps prevent logically expired keys from accumulating in other databases while one database is repeatedly processed.
Without the comment, the code looks harmless: "Select, increment, go to do some work."
There is no evident reason for not relocating the increment at the end of the loop, where it could look more natural.
During the replication handshake, the output buffer accumulates changes between the BGSAVE and the current dataset. We need a fresh reply buffer registering the differences between the BGSAVE and the current dataset so that we can copy to other replicas if needed. Pending output therefore makes SYNC and PSYNC invalid.
The expiration loop uses the condition j < dbs_per_call && timelimit_exit == 0. It selects the database with server.db+(current_db % server.dbnum).
The comment says: Increment the DB now so we are sure if we run out of time. Advancing before processing means the next call can start with another database if the current one exhausts its time budget, distributing work across databases.
The expiration-loop increment was indeed at the end in the original code. It was moved there during a fix: at the same time the comment was added. The comment records why the non-obvious placement should be preserved during refactoring.
I treat why-comments as opportunities to reconsider system complexity. However often making something simpler may make something else harder or is simply not viable, or requires future work breaking backward compatibility.
I distinguish function comments from design comments. Function comments state the rules callers can rely on; design comments explain the higher-level approach and its rationale. Both help readers understand code without reconstructing its purpose from the implementation.
I want a function comment to prevent the reader from reading code in the first place.
After reading a function comment, it should be possible to consider some code as a black box that should obey certain rules.
Function comments are normally at the top of functions definitions, but they may be at other places, documenting classes, macros, or other functionally isolated blocks of code that define some interface.
I describe function comments as a form of in-line API documentation.
When a function comment is written well enough, I can usually return to the calling code without reading the function’s implementation.
Function comments are among the kinds of comments most widely accepted by the programming community as necessary.
I want the API documentation to exactly match the code.
As the code is changed, the documentation should be changed.
Keeping API documentation close to definitions makes it more likely that the author of a change, who understands it best, will also update the documentation; it also avoids context switching between code and separate documentation.
A design comment is more often located at the start of a file.
A design comment states how and why a given piece of code uses certain algorithms, techniques, tricks, and implementation.
A design comment is a higher-level overview of what the reader will see implemented in the code.
In bio.c, the design note describes a structure representing a job to perform.
With such background, reading the code will be simpler.
I tend to trust more code where I can find design notes, because they indicate that some kind of explicit design phase happened during development.
For rax.c, the comment for raxSeekGreatest says it seeks the greatest key in the subtree at the current node, returns 0 on out of memory and otherwise 1, and is a helper for iteration functions below.
Design comments can explain what were the competing solutions and why a very simple solution was considered to be enough for the case at hand.
When a design is correct, explaining the alternatives can help readers see that simplicity comes from a considered process, not from being lazy or only knowing how to code basic things.
The bio.c design note describes a structure representing a job to perform, a different thread and job queue for every job type, and each thread waiting for new jobs in its queue and processing every job sequentially.
I argue that writing comments is of paramount importance in order to produce good code, that is maintainable in the long run and understandable by others and by the authors during modifications and debugging activities.
I explain that often this missing information is why the code is doing a certain action, or why it’s doing something that is clear instead of something else that would feel more natural.
I see comments as a way to reduce the reader’s effort and the number of details they need to hold in mind: So comments can be, for me, a tool for lowering the cognitive load of the reader.
I also make the case for comments stating what the code is doing, and not why, as potentially useful rather than automatically redundant or dangerous.
I began the research by reading random parts of Redis source code: The way I started this work was by reading random parts of the Redis source code, to check if and why comments were useful in different contexts.
I identified nine types of comments: nine. The categories are Function comments, Design comments, Why comments, Teacher comments, Checklist comments, Guide comments, Trivial comments, Debt comments, and Backup comments.
My assessment is: The first six are, in my opinion, mostly very positive forms of commenting, while the final three are somewhat questionable.
I used Redis source snippets from the current "unstable" with hash 32e0d237.
The captured page metadata reads: 2976 days ago. 457064 views.