Book Review of "The Practice of Programming" (Ⅰ)

The Practice of Programming

 

In the preface, the author illustrates four basic principles of programming - simplicity, clarity, generality, automation.

I suppose that everyone has his own programming experience and preference, but with predecessors' valuable guidence, chances are that we can write more beautiful code.

Pieces of summaries and abstracts are organized as follows:

 

Charpter 1 STYLE

The purpose of style is to make the code easy to read for yourself and others, and good style is crucial to good programming.

 

  Names

  • descriptive names for globals, short names for locals
  • names with p for pointers; initial capital letters for Globals; all capitals for CONSTANTS; active names for functions
  • be consistent

 

  Expressions and Statements

  • avoid negative expressions possibly
  • use parentheses in mixed unrelated operators
    1 the relational operators (< == !=) have higher precedence than the logical operators (&&  || );
    2 the logical operators bind tighter than assignment ( = );
    3 the bitwise operators (&  |) have lower precedence than relational operators ( == )
  • break up complex expressions
  • be careful with side effects:  (e.g. the following expression is wrong)
    scanf("%d %d", &yr, &profit[yr]);X  

 

  Consistency and Idioms

  • Use a consistent indentation and brace style
  • Use idioms for consistency
    Wrong code:
    gets(buf);X  //never use 'gets', 'fgets' is better
    p = malloc(strlen(buf));
    strcpy(p, buf);X  //strlen does not count the '\0' that terminates a string, while strcpy copies it
    Right code:
    p = malloc(strlen(buf)+1);
    strcpy(p, buf);
  • the return value from malloc, realloc, strdup, or any other allocation routine should always be checked

 

  Function Macros

  • One of the most serious problems with function macros is that a parameter that appears more than once in the definition might be evaluated more than once

 

  Magic Numbers

  •  By giving names to the principal numbers in the calculation, we can make the code easier to follow

  •  Define numbers as constants, not macros

    const int MAXROW = 24. MAXCOL = 80;
    static final int MAXROW = 24, MAXCOL = 80;
    C also has const values but they cannot be used as array bounds, so the enum statement remains the method of choice in C.
  •  Use the language to calculate the size of an object

    sizeof (int)
    sizeof(array[0])
    sizeof(buf)

  

  Comments

  • Comment functions and global data
  • Sometimes code is genuinely difficult, perhaps because the algorithm is complicated or the data structures are intricate. In that case, a comment that points to a source of understanding can aid the reader

  • Don't comment bad code, rewrite it

  • Don't contradict the code. When you change code, make sure the comments are still accurate

 

你可能感兴趣的:(Book Review of "The Practice of Programming" (Ⅰ))