←back to thread

1455 points nromiun | 1 comments | | HN request time: 0.263s | source
Show context
Buttons840 ◴[] No.45075079[source]
It's been said: "Document the why, not the what."

I have a hard time separating the why and the what so I document both.

The biggest offender of "documenting the what" is:

    x = 4  // assign 4 to x
Yeah, don't do that. Don't mix a lot of comments into the code. It makes it ugly to read, and the context switching between code and comments is hard.

Instead do something like:

    // I'm going to do
    // a thing. The code
    // does the thing.
    // We need to do the
    // thing, because the
    // business needs a
    // widget and stuff.
    
    setup();
    t = setupThing();
    t.useThing(42);
    t.theWidget(need=true);
    t.alsoOtherStuff();
    etc();
    etc();
Keep the code and comments separate, but stating the what is better than no comments at all, and it does help reduce cognitive load.
replies(6): >>45075259 #>>45075314 #>>45075395 #>>45076149 #>>45079235 #>>45080058 #
dsego ◴[] No.45075395[source]
> x = 4 // assign 4 to x

Ah, the chat gpt style of comments.

> Instead do something like:

The only negative is that there is a chance the comment becomes stale and not in sync with the code. Other coders should be careful to update the comment if they touch the code.

replies(1): >>45075474 #
Buttons840 ◴[] No.45075474[source]
If the what becomes stale, you can tell. If the why becomes stale (and it can become stale), you'll never know, unless the what is also included.
replies(2): >>45075786 #>>45076785 #
1. fcantournet ◴[] No.45076785[source]
The why becoming stale is a feature, that's when you know there is a VALID reason you thought this looked weird and convoluted, instead of you completely missing the inherent complexity of the problem.