Skip to contentSkip to conversation

Coding Style

OT? Stephen Satchell 6 participants 7 messages Jan 22, 2001 – Jan 23, 2001

lore
Share & tools
lore
#0 lore raw
Quoted 10 lines · you

WRONG!!!

Not documenting your code is not a sign of good coding, but rather shows arrogance, laziness and contempt for "those who would dare tamper with your code after you've written it". Document and comment your code thoroughly. Do it as you go along. I was also taught to comment nearly every line - as part of the coding style used by a large, international company I worked for several years ago. It brings the logic of the programmer into focus and makes code maintenance a whole lot easier. It also helps one to remember the logic of your own code when you revisit it a year or more hence.

Oh, those who refuse to study history are doomed to repeat it.

The COBOL language was created specifically to reduce the amount of commenting necessary in a program, because the English-like sentence structure could be read and understood by humans. The FORTRAN language was created so that math types could "talk" in a language more familiar to them, letting the computer take care of the details about how to perform the specified task step-by-step.

One goal of language designers is to REMOVE the need for comments. With a good fourth-generation or fifth-generation language, the need for comments diminishes to a detailed description of the data sets and any highly unusual operations or transforms on the data.

I've even gone so far as to "invent" my own languages, and the parsers to go with them, to reduce the need to comment by making the code easy for humans to read. Not only are such systems easier to debug (with good language design) but are highly maintainable and usually not all that difficult to extend when necessary.

Remember, the line-by-line commenting requirement was mandatory in assembler programming, because the nature of assembler made you outline each step by tiring step. When I worked for Rockwell, I was granted a partial wavier when I showed them my assembler-language commenting style: pseudo-code at the top of each block of assembler code. Blindly applying the rule to second-generation and later languages is just sloppy management, usually by people who don't understand coding. (And yes, that includes some professors of computer science I have known.)

Comments do NOT make code maintenance easier. Too many comments obscure what is really going on. Linus' style actually increases the maintainability of the code, because if the code doesn't accurately show how it implements the goal specified in the block comment, the coder hasn't done his/her job.

Want to improve the maintainability of C code? Consider the following:

1) Keep functional parts small. If the code won't fit in a hundred lines or so of code, then you haven't factored the problem well enough. Functional parts != functions. A program with thousands of well-encapsulated function parts strung together into a single function is easier to maintain than a "well-factored" program with its parts spread all over hell. Diagnostic programmers have learned the hard way that factoring a program can make it difficult to ensure test coverage and even more difficult to determine if a part of the code is buggy or whether it found a hardware error that it was looking for. This is why diagnostics tend to be rather long affairs with very few functions.

In my ANSI C code, you will see the following a lot:

#define DO /*syntactic sugar */

    DO {
       </* first functional part, with owned variables */
    }

    DO {
        </* next functional part, with its owned variables */
    }

and so forth. The "DO" is visual syntactic sugar so that the sub-blocks have the same appearance as other blocks, such as if, while, and for. An added bonus to this particular style element is that compilers can more easily detect problems if you forget to initialize the local variables, or define variables you end up not using. This has saved me hours of tedious debugging of my own code. From the maintenance standpoint, it means that the definition of local variables are near all usages of it, so you don't have to continuously page up or split-screen to see the definition (and initialization) of "foobar_at_will".

2) Reduce visual complexity where possible. Instead of using nested if-then-else statements, consider unrolling the nested statement. Example: {if (a && c)...; if (b && c)...; instead of {if (c) {if (a)...; if(b)...;}

This doesn't have to affect performance. For example, you can have rules such as:

     ruleset = (a ? 1 : 0) | (b ? 2 : 0) | (c ? 4 : 0);
     if (ruleset == 5) {
     ...
     }
     if (ruleset == 6) {
     ...
     }

This particular method can eliminate multiple expensive tests, and can guarantee that a, b, and c are evaluated exactly once during a cycle. This can improve performance. Using AND, OR, and XOR can further increase the power of the technique without a performance hit. (For understandability, I recommend strongly a considered use of symbolic bitmasks, however.)

3) Make creative use of a run-on if statement to improve error detection and recording. One of my tricks is to code the following statement in application programs:

if( (err = "input file can't be opened", in = fopen(filename,
"rb"), in == NULL)

       ||  (err = "output file can't be opened", out = fopen(oname, "wb"), 
out = NULL)
       ...
         )
      {
      /* report the error that occurred, using the char * variable "err" 
to indicate the exact error. */
      }

This means that I don't have to explicitly remember to code error routines for each and every function call, but the error detection coverage is much, much improved. I used this technique in an IEEE-488 driver to detect errors in every step of the way, and it took LESS time to do it this way than to unroll the if statement because of the inherent tracing that the technique implements.

4) The functional part should be contained in a reasonable number of lines. Large while and for loops should call functions instead of having bloated bodies. Large case statements should call functions instead of running on and on and on.

5) For those statements that take compound statements (if, else, while, for, do while) the statement should ALWAYS be a compound statement. Nothing introduces bugs faster than a tired programmer not realizing that he/she is inserting a statement in the target of one of these statements and thereby replacing the target with a new one. This one issue has broken more patches in my experience than any other single item.

The argument that "this introduces a blizzard of unnecessary braces" is overweighed by the guarantee that the programming coming down the pike later won't accidentally remove a target line because s/he is too tired or rushed to recognize that s/he has to ADD BRACES (and in the case of a severely nested statement where to add braces) in order to turn a single-line target into a two-line target. (Of course, some of you never make mistakes like that. Fine.)

6) When you have an "empty" statement as the compound statement, indicate it unambiguously. I have yet to find a see compiler that doesn't handle the following construct correctly:

     while (wait_for_condition())
        {}

(or, more in keeping with Linus' style without adding an extra line, "while (wait_for_condition()) {}" )

The "{}" signal (familiar to those of you who are adept with xargs) indicates that nothing is being done, and does it far more readily than a single semicolon can ever signal. If I could make just one change to the C language, I would REQUIRE that a non-empty statement or possibly empty compound statement be the only valid targets for if, else, do while, for, and while statements.

7) Name space pollution is always a problem, although in these days of computer with gigabytes of RAM it's less of a problem than it used to be. I started programming C when my main computer had 256K of RAM and the symbol table space for linking was limited. I got in the habit of using structures to minimize the number of symbols I exposed. It also disambiguates local variables and parameters from file- and program-global variables. This name-space management ensures that you don't accidentally redefine in an inner block a variable that you think is a global. In very large programs, it also avoids name collisions between portions of the project.

Style has little to do with art. Style has to do with minimizing mistakes, both now and down the road. If you don't like what I do, then don't do what I do. Do what minimizes mistakes for you.

And, Linus, I'm not recommending you adopt any of these suggestions -- you have your way and I have mine. If you like any of these, though, feel free to take them for your own. File off the serial numbers, and enjoy.

Stephen Satchell

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
Please read the FAQ at http://www.tux.org/lkml/

#1 lore raw
Quoted 2 lines · Stephen Satchell

One goal of language designers is to REMOVE the need for comments. With a

this is a crock of (deleted). You are chaising rainbows dood, you will NEVER remove teh need for comments but its obvious you remove teh comments.

Quoted 3 lines

good fourth-generation or fifth-generation language, the need for comments diminishes to a detailed description of the data sets and any highly unusual operations or transforms on the data.

sorry but i could not disagree more

Quoted 6 lines

I've even gone so far as to "invent" my own languages, and the parsers to go with them, to reduce the need to comment by making the code easy for humans to read. Not only are such systems easier to debug (with good language design) but are highly maintainable and usually not all that difficult to extend when necessary.

no lprogramming anguage can describe describe the design of the applications written in it. you NEED to comment your code. 100% Self commenting code is a falacy. 50% self commenting code is almost impossible to achieve. COMMENT IT!

Quoted 4 lines

Remember, the line-by-line commenting requirement was mandatory in assembler programming, because the nature of assembler made you outline each step by tiring step.

You talk like you dislike assembler as much as i dislike c :)

Quoted 3 lines

When I worked for Rockwell, I was granted a
partial wavier when I showed them my assembler-language commenting
style: pseudo-code at the top of each block of assembler code.

very ugly. The S4 meter from landys and gyr (now siemens) actually uses c code above each assembler routine as a form of commeting. using code to comment code is fine as long as you COMMENT the comments!

Quoted 2 lines

Comments do NOT make code maintenance easier. Too many comments obscure what is really going on.

well... i disagree, years of consulting work and having to deal with hunks of legacy code with no comments and huge functions etc etc et (every coders worst nightmare) has taught me that comments are very much needed (even bad comments are preferable to none at all)

Quoted 4 lines

Linus' style actually increases the
maintainability of the code, because if the code doesn't accurately show how it implements the goal specified in the block comment, the coder hasn't done his/her job.

TRUE. Code should be written well enough that it isnt naturally obfuscated but this does NOT remove the need for comments.

Quoted 10 lines

Want to improve the maintainability of C code? Consider the following:

1) Keep functional parts small. If the code won't fit in a hundred lines or so of code, then you haven't factored the problem well enough. Functional parts != functions.

A program with thousands of
well-encapsulated function parts strung together into a single function is easier to maintain than a "well-factored" program with its parts spread all over hell.

Cram a gazillion simple operations into a single function and you end up with chaos, totally unfactored code is almost impossible to read.

Quoted 4 lines

Diagnostic programmers have learned the hard way that factoring a program can make it difficult to ensure test coverage and even more difficult to determine if a part of the code is buggy or whether it found a hardware error that it was looking for.

then they dont know how to test a program. period

Quoted 14 lines

In my ANSI C code, you will see the following a lot:

#define DO /*syntactic sugar */

     DO {
        </* first functional part, with owned variables */
     }

     DO {
         </* next functional part, with its owned variables */
     }
Quoted 4 lines

2) Reduce visual complexity where possible. Instead of using nested if-then-else statements, consider unrolling the nested statement. Example: {if (a && c)...; if (b && c)...; instead of {if (c) {if (a)...; if(b)...;}

which is simpler...

(x + y) ^ 2

or...

(x ^2) + (Y ^2) + 2xy

Quoted 10 lines

3) Make creative use of a run-on if statement to improve error detection and recording. One of my tricks is to code the following statement in application programs:

if( (err = "input file can't be opened", in = fopen(filename,
"rb"), in == NULL)

        ||  (err = "output file can't be opened", out = fopen(oname, "wb"),
out = NULL)
        ...
          )

use clever little tricks in your c so as to confuse people ? You are obviously a very advanced c coder who knows well the intracasies of the language. The person who has to maintain your code 10 years after you have left may not be.

Quoted 4 lines
       {
       /* report the error that occurred, using the char * variable "err"
to indicate the exact error. */
       }

granted, the above block of code was not that difficult to understand, even tho I have never seen that particular trick used before but the above statement still stands. (nice trick btw :)

Quoted 4 lines

4) The functional part should be contained in a reasonable number of lines. Large while and for loops should call functions instead of having bloated bodies. Large case statements should call functions instead of running on and on and on.

i wish everyone understood this (not usually a failing within the linux kernel but you should see some of the code I have had to deal with. doh! :)

Quoted 6 lines

5) For those statements that take compound statements (if, else, while, for, do while) the statement should ALWAYS be a compound statement. Nothing introduces bugs faster than a tired programmer not realizing that he/she is inserting a statement in the target of one of these statements and thereby replacing the target with a new one. This one issue has broken more patches in my experience than any other single item.

by always adding braces to your if/else statements etc the above becomes alot simpler me thunks... -->

Quoted 7 lines

The argument that "this introduces a blizzard of unnecessary braces" is overweighed by the guarantee that the programming coming down the pike later won't accidentally remove a target line because s/he is too tired or rushed to recognize that s/he has to ADD BRACES (and in the case of a severely nested statement where to add braces) in order to turn a single-line target into a two-line target. (Of course, some of you never make mistakes like that. Fine.)

erm something is wrong here, i am actually agreeing with this guy ??? erm i think i need to go lie down for a while, i dont feel so good :)

Quoted 6 lines

6) When you have an "empty" statement as the compound statement, indicate it unambiguously. I have yet to find a see compiler that doesn't handle the following construct correctly:

      while (wait_for_condition())
         {}

while ( ... ) // is good but the above looks much nicer
;

Quoted 2 lines

(or, more in keeping with Linus' style without adding an extra line, "while (wait_for_condition()) {}" )

this i dislike, ites easy for the eye to pass over the {} but STILL not quite as bad as...

    while ( ..... );		// yukk :)
Quoted 3 lines

7) Name space pollution is always a problem, although in these days of computer with gigabytes of RAM it's less of a problem than it used to be.

well ok... less of a problem for the COMPUTER :)

Quoted 2 lines

I started programming C when my main computer had 256K of RAM and the
symbol table space for linking was limited.

should have been coding asm :)

Quoted 4 lines

I got in the habit of using
structures to minimize the number of symbols I exposed. It also
disambiguates local variables and parameters from file- and program-global variables.

explain this one to me, i think it might be usefull...

Quoted 3 lines

Style has little to do with art. Style has to do with minimizing mistakes, both now and down the road. If you don't like what I do, then don't do what I do. Do what minimizes mistakes for you.

style can show your art though, no style usually means no art :) -
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
Please read the FAQ at http://www.tux.org/lkml/

#2 lore raw
Quoted 7 lines · Mark I Manning IV
Quoted 4 lines · Stephen Satchell

I got in the habit of using
structures to minimize the number of symbols I exposed. It also
disambiguates local variables and parameters from file- and program-global variables.

explain this one to me, i think it might be usefull...

What might be meant is that instead of declaring variables my_module_var1, my_module_var2, my_module_var3, etc. you declare a struct my_module { var1; var2; var3; etc. }. Obviously in glorious technicolour formatting... (-; That's my interpretation anyway...

Anton

Signature · 12 lines
     "Education is what remains after one has forgotten everything he 
learned in school." - Albert Einstein
-- 
Anton Altaparmakov  Voice: +44-(0)1223-333541(lab) / +44-(0)7712-632205(mobile)
Christ's College    eMail: [email protected] / [email protected]
Cambridge CB2 3BU    ICQ: 8561279
United Kingdom       WWW: http://www-stu.christs.cam.ac.uk/~aia21/

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to [email protected]
Please read the FAQ at http://www.tux.org/lkml/
#4 lore raw
In reply to Stephen Satchell
Quoted 7 lines · Anton Altaparmakov
Quoted 6 lines · Mark I Manning IV
Quoted 4 lines · Stephen Satchell

I got in the habit of using
structures to minimize the number of symbols I exposed. It also
disambiguates local variables and parameters from file- and program-global variables.

Quoted 6 lines
Quoted 1 line

explain this one to me, i think it might be usefull...

What might be meant is that instead of declaring variables my_module_var1, my_module_var2, my_module_var3, etc. you declare a struct my_module { var1; var2; var3; etc. }. Obviously in glorious technicolour formatting... (-; That's my interpretation anyway...

Mine too and I think it's a good idea. I have code in BitKeeper where I both did and did not do that for command line options and I much prefer the structure version.

Another habit I used to use and have fallen out of, which is a bad idea, is one where you use a prefix in stucture files so that you can see the difference between

	p->st_mode
and
	p->f_mode

In other words, the prefix implies the structure name. Early versions of the C compiler had all structure fields (I mean _all_) in one name space so this wasn't style, it was required. I must say that it makes code more readable.

Signature · 6 lines
---
Larry McVoy            	 lm at bitmover.com           http://www.bitmover.com/lm 
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to [email protected]
Please read the FAQ at http://www.tux.org/lkml/
#3 lore raw
In reply to Anton Altaparmakov
Quoted 11 lines · Anton Altaparmakov
Quoted 7 lines · Mark I Manning IV
Quoted 4 lines · Stephen Satchell

I got in the habit of using
structures to minimize the number of symbols I exposed. It also
disambiguates local variables and parameters from file- and program-global variables.

explain this one to me, i think it might be usefull...

What might be meant is that instead of declaring variables my_module_var1, my_module_var2, my_module_var3, etc. you declare a struct my_module { var1; var2; var3; etc. }. Obviously in glorious technicolour formatting... (-; That's my interpretation anyway...

The first sentence is right on the money. In addition to module variables, I define a global structure as:

     extern struct G {
         /* the real globals */
         } g;

and then in the main program I define the instance as "struct G g;" This is more for apps than operating systems.

Further to the avoidance of pollution of the external global namespace, I define local functions as static. Indeed, in one parser I had over 1400 very small functions, none of them with external scope. Instead, I defined a structure of function pointers and exposed one name to the rest of the world. Sound stupid? Well, that stupidity had its place: the "opcode" in the pseudo-instruction stream was the offset into this structure of pointers to the pointer of interest, which made the main loop for the parser about five lines long, and not a switch statement to be seen. Three of those lines were to handle unknown-opcodes...

I also am partial to arrays of function pointers when appropriate. Ever think how easy it would be to implement a TCP stack that would handle the "lamp-test packet" as a single special case? Granted, it results in a small amount of code bloat over the traditional in-line test method, but it does make you think about EVERY SINGLE ONE OF THE 64 COMBINATIONS of Urg/Ack/Psh/Rst/Syn/Fin (to use the labels from the 1985 version of RFC 793) and what they really mean. Especially the combination with all bits set.

Satch

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
Please read the FAQ at http://www.tux.org/lkml/

#5 lore raw
In reply to Stephen Satchell

Stephen Satchell wrote:

[lots of good advice deleted]

Quoted 4 lines

One goal of language designers is to REMOVE the need for comments. With a good fourth-generation or fifth-generation language, the need for comments diminishes to a detailed description of the data sets and any highly unusual operations or transforms on the data.

This is but a dream. You can't "design out" the need for comments by approaching natural language. Try reading a law book and realize that natural language too may be twisted to the extent that it needs extensive comments. The same goes for any computer language powerful enough to do useful work.

Helge Hafting
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
Please read the FAQ at http://www.tux.org/lkml/

#6 lore raw
Quoted 8 lines · Helge Hafting

Stephen Satchell wrote:

[lots of good advice deleted]

Quoted 4 lines

One goal of language designers is to REMOVE the need for comments. With a good fourth-generation or fifth-generation language, the need for comments diminishes to a detailed description of the data sets and any highly unusual operations or transforms on the data.

Quoted 5 lines

This is but a dream. You can't "design out" the need for comments by approaching natural language. Try reading a law book and realize that natural language too may be twisted to the extent that it needs extensive comments. The same goes for any computer language powerful enough to do useful work.

Actually using natural language and other such constructs may INCREASE the need for comments.

For more examples, see Perl.

[email protected] | Note to AOL users: for a quick shortcut to reply
Alan Olsen | to my mail, just hit the ctrl, alt and del keys.
"In the future, everything will have its 15 minutes of blame."

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to [email protected]
Please read the FAQ at http://www.tux.org/lkml/