Control Flow Block Code Comments

:waving_hand:

Is there a convention for where to place code comments for blocks?

Specifically, in cases where a branch is explained, is there a convention for the comment to go above or within the block declaration?

Example

// Comment about branch where `c` is Some
let a = if let Some(b) = c {
    a_from_b(b)
    // Comment about branch where `d` and `e` are equal
} else if d == e {
    a_from_d(d)
    // Comment about branch where neither are the case
} else {
    a_from_neither()
}

Versus

let a = if let Some(b) = c {
    // Comment about branch where `c` is Some
    a_from_b(b)
} else if d == e {
    // Comment about branch where `d` and `e` are equal
    a_from_d(d)
} else {
    // Comment about branch where neither are the case
    a_from_neither()
}

Yes, I know this is bikeshedding

people like bikeshedding anyways. :wink:

anyways, I personally like to put comments before the code, and this is what I usually do:

// Comment about branch where `c` is Some
let a = if let Some(b) = c {
    a_from_b(b)
}
// Comment about branch where `d` and `e` are equal
else if d == e {
    a_from_d(d)
}
// Comment about branch where neither are the case
else {
    a_from_neither()
}
3 Likes

If you feel the need to comment, you should rewrite the code to make it self-explanatory.

I can't find anything in the style guidelines, nor a clippy lint. Rustfmt also doesn't reformat the comments of either of your snippets.

While that's good advice in the general case, there are cases when comments can provide valuable context. As with other "best practices" in programming, the sweet spot is somewhere in between the extremes.

My point is, OP's question is still valid.

3 Likes

I place the comments as the first line(s) inside the if. I think this is where they belong semantically. Anything else just feels wrong to me.

1 Like

I agree and I say to the OP: It depends.
Your example is obviously fabricated, so I cannot give you advice on that.
If you can provide a real-life example of such a situation, I might give you advice on a case-by-case basis.