* Ingo Molnar <mi...@kernel.org> wrote:
> With tail comments the code looks like this: > > res = dostuff(); /* We explain something here. */ > > seed = 1; /* Another explanation. */ > > mod_timer(&our_object->our_timer, jiffies + OUR_INTERVAL); /* We like > to talk */ > > res = check_stuff(our_object); /* We explain something here. */ > if (res) > return -EINVAL; > > interval = nontrivial_calculation(); /* Another explanation. */ > > mod_timer(&our_object->our_timer, jiffies + interval); /* This doesn't > race, because. */ > > ... while with freestanding comments it's: > > /* We explain something here: */ > res = check_stuff(our_object); > if (res) > return -EINVAL; > > /* Another explanation: */ > interval = nontrivial_calculation(); > > /* This doesn't race with init_our_stuff(), because: */ > mod_timer(&our_object->our_timer, jiffies + interval); > > This comment placement style has several advantages: > > - Comments precede actual code - while in tail comments it's exactly > the wrong way around. > > - We don't create over-long lines nor artificially short tail comments > just because we were trying to stay within the col80 limit with the > "this doesn't race" comment. The full-line comment was able to > explain that the race is with init_our_stuff(). > > - Freestanding oneliner comments are much better aligned as well: note > how ever comment starts at the exact same column, making it very easy > to read (or not to read) these comments. > > - In short: predictable visual parsing rules and proper semantic > ordering of information is good, random joining of typographical > elements just to create marginally more compact source code is bad. > > - Just *look* at the tail comments example: it's a visually diffuse, > jumble of statements and misaligned comments with good structure. Forgot to mention the role of punctuation: - Also note how punctuation actually *helps* the integration of comments and code. The ":" will direct attention to the code that follows, making it clear that the sentence explains the next statement. There are exceptions for when different type of punctuation is a better choice, for example: /* TODO: convert the code to our newest calc API ASAP. */ interval = nontrivial_calculation(); Here we don't explain the statement but document a TODO entry. Also, it's frequent practice to use multi-line comments to explain the next section of code, with a particular note about the first statement. Proper punctuation helps there too: /* * Establish the timeout interval and use it to set up * the timer of our object. The object is going to be * freed when the last reference is released. * * Note, the initial calculation is non-trivial, because * our timeout rules have complexity A), B) and C): */ interval = nontrivial_calculation(); Note how part of the multi-line comment describes overall principles of the code to follow, while the last sentence describes a noteworthy aspect of the next C statement. Thanks, Ingo