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()
}
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()
}
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.
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.