"Programming Craftsmanship" Reading Notes (1)

foreword

I recently read the book "Programming Craftsmanship", which was written by American author Pete Goodliffe. It is not only a study guide, but also a book that stimulates the passion for programming, showing a programming attitude of pursuing excellence.

In my opinion, it brings not only technical improvements, better mastery of programming skills, improvement of one's own development efficiency and quality, but more importantly, thinking and understanding of programming.

The following are reading notes + personal understanding. The book is divided into 24 chapters, currently chapter 01-06.

1. Defensive programming

1.1 Good code

There are three codes

  • Working code: It is fine for regular input, but may crash when encountering unexpected input
  • Correct Code: This code will never crash, but the input set can be large and difficult to test and sometimes understand
  • Good code: This kind of code will first be correct, and then it will be robust and efficient

I think that the first chapter in the book "Java Confusion" is the code to judge whether an integer is odd or not. After modification, it will change from usable to excellent.

// 碰到负整数会有问题
public static boolean isOdd(int i) {
    
    
    return i%2==1;  
}
// 修改后
public static boolean isOdd(int i) {
    
    
    return i%2!=0;  
}

1.2 Defensive programming techniques

It seems easy to write good code by yourself, but it is very difficult to write good code when you cooperate with others or take over the old code. At this time, defensive programming needs to be used.

  • Don’t make assumptions, just like the above judge whether it is odd or not, you can’t imagine that the program will only input positive integers. A person may remember the code for a short time, but after a long time or when other people call your code during teamwork, they will not consider it. These
  • Use good coding style and design
  • Can't write code hastily
  • Do not trust anyone
  • The goal of coding is clarity, not brevity. You can't just consider one line of code to solve it, but it should be easy to understand, whether you are yourself or others
  • Each performs its own duties. In java development, bean properties should be set as private, and I think the responsibilities of the class should match the name, and do not add irrelevant methods.
  • Turn on all warning switches at compile time, this is for C/C++
  • Use static analysis tools
  • Use safe data structures
  • Check all return values
  • Handle memory (or other precious resources) carefully for C/C++
  • Variables are initialized at the declaration position, for C/C++, Java declarations have default values
  • defer some variable declarations as much as possible
  • Use standard language tools for C/C++
  • Use a good diagnostic logging tool, Java has log4j
  • Use coercion with caution
  • Provide default behavior, switch default and if else carefully consider various situations
  • Consider number overflow
  • Set all variables that can be set as constants to constants

1.3 Constraints

C and C++ constrain code through assert assertion, and Java can also constrain code through assert statement

2. Code style

2.1 For humans

We write code for three categories of readers:

  • Myself: My handwriting is ugly, and it is difficult for me to read, let alone the code
  • Machine: The machine does not care about the style, it only needs to be compiled, and it will not report an error because of the style
  • Others: This type of person is the most important, individual abilities are always limited, and people need to cooperate to complete tasks

So the code style is human-oriented, and the machine doesn't care about it. The style of an excellent programmer is definitely different from that of a novice. The code style written by a novice is always confusing. Look at the code you wrote back then.

2.2 Excellent style

Good styles have the following characteristics:

  • Consistent: the number of indentation spaces must be consistent, the position of curly brackets must also be consistent, etc.
  • Traditional: Use a specification that is popular in the industry
  • Simplicity: simple, easy for others to learn, acceptable

Good style is not static, it must be accepted by most people in the team

3. Code naming

3.1 Naming Why What How

  • Why Good Naming Matters

    What has a name exists, and a good name is easy to understand and remember. Poorly named entities are not only inconvenient to manage, but also misleading and error-prone during programming. The name of an object should clearly describe the object

  • what to name

    Variables, functions, classes, namespaces, packages, macros, source files, etc. These are the most common ones in programming

  • how to name

    see below

3.2 Good Naming

  • Technically correct, the compiler will not report an error

  • Emphasis on clarity over brevity, no ambiguity

  • In line with language habits, consistent, unified

  • Using the context, if the class Tree has a method countApplesInTree, it can be changed to Tree:countApples

3.3 Variable naming

  • Nouns: usually represent a physical object, and some variables that cannot correspond to real objects can also use nouns, such as the elapsed time elapsed_time

  • Verb: If the variable cannot be represented by a noun, then it is generally a nominalized verb, such as count count

  • The name of a numeric variable describes the interpretation of its value, such as widget_length

  • The name of the logical variable is a conditional statement form name, such as is_red

  • Variables and types should be distinguished, so the first letter of a variable is generally lowercase, while the type is uppercase

3.4 Function Naming

  • A function is an action, and the name contains at least one verb
  • Naming functions from the user's point of view
  • You can use underscore or camelCase to name

3.5 Type Naming

  • A type can describe some data object with state, in which case the name may be a noun

  • The type may also be a class implementing an interface callback function, in this case, the name may be a verb

4. Code self-documentation

4.1 Why you are reluctant to write documentation

  • Most programmers have a headache for text work and a headache for writing a large number of comments, and writing documents is time-consuming, as is reading, so they prefer to write programs
  • All individual docs are updated as the code changes, which is a horrible job in large projects
  • A large number of documents are difficult to manage and must be version controlled like code
  • External documents and programs are difficult to link and it is easy to miss important information

4.2 Self-documenting code

  • Self-documenting code is beautiful, highly readable code that is easy to understand on its own and requires no external documentation.
  • Ideally, self-documenting code does not require comments, which will affect reading, but it is actually difficult to do, so good comments are required

4.3 Tips

  • good style
    • Keep the structure consistent in if/else (for example, always handle the correct case after the if, and handle the error case after the else), and keep it unified, and the situation cannot be reversed later
    • Avoid excessive nesting, use recursion sparingly
    • Carefully optimize code
  • decomposed into atomic functions
    • A function that performs only one operation, choose a name that unambiguously describes the operation, a good name does not require additional documentation
    • reduce any unintended side effects
    • Keep it short, small functions are easy to understand
  • Choose the right type
    • Values ​​that never need to be modified can be defined as constants
    • If the value described by the variable does not contain negative values, the unsigned type should be used (if the language supports it)
    • Use an enum to describe a set of related values
    • Choose the appropriate type. C/C++ puts the size of the value in the size_t variable, and puts the operation result of the pointer into the ptrdiff_t variable
  • named constant
    • if (count == 76)What is the meaning of 76 in the middle, modify 76 to the constant banaba_per_cake for better understanding
    • The above-mentioned 76 is called a Magic Number, and some code detection tools will detect it
  • Emphasize important code
    • Must be declared in order in the class. Put public information first and private implementation information last
    • Hide all unimportant information
    • Don't hide important code
    • Limit the number of nested conditional statements
  • Group related information
    • All relevant information should be in one place
    • There are packages in java that provide grouping
    • c/c++ has a namespace
  • Provide header
    • Provide a comment block at the top of the file to describe the role of the file for easy understanding by maintainers
    • Most companies or a lot of open source software will add a copyright or open source statement to each source file for legal considerations
  • Handle errors appropriately
    • Proper place to handle errors. If the disk IO is abnormal, the exception should be handled in the code that accesses the disk. This exception will also cause a file inaccessible exception, so IO errors cannot be handled here
    • Don't handle disk IO errors in the final UI code section
  • Write meaningful comments
    • Only add comments if you cannot improve code clarity in any other way
  • Improve your own level
    • Writing skills can be improved by reading more books. Use a critical eye to examine other people's articles, you can learn to distinguish good from bad
    • The same is true for writing code. Reading various excellent codes (various open source libraries) will also improve your personal level

Five, code comments

5.1 Function

  • Comments can distinguish good code from bad code, rough and complex logic from clear and friendly algorithms, but the role of comments should not be overstated.
  • Comments can be icing on the cake, but they can't help you in the snow, and you can't make the sour code sweet

5.2 what is

  • From a syntactic point of view, it is a source code block ignored by the compiler, and from a semantic point of view, it is an interpretation of the code in which it is located
  • The target readers of comments are people, and to improve the quality of comments must meet the real needs of people when reading code
  • As a responsible programmer, it is obligatory to write good comments

5.3 What to write

  • explain why, not how

  • Do not repeat code in comments

  • When writing dense comments to explain code, you should optimize the code, not write the comments

  • Log something unexpected, such as an operating system problem

  • Written text must be truthful, valuable, clear and understandable

5.4 What not to write

  • In the past, don't write the code of the past version, now there is a version control system, you can find the code and comments of the past

  • Unwanted code, also has a code version control system,

  • ASCII art, any style that highlights code parts is not advisable, examples are as follows

    aBadExample(n, foo(wibble));
    //             ^^^
    //             My favorite function
    
  • At the end of the code block, it is not advisable to mark the end of the control block with a comment. Modern editors have a code block folding function, which is easy to distinguish

    // end if (a < 1)
    

5.4 Usage Notes

  • Add TODO in comments to mark unfinished work
  • Use comments Be careful to delete obsolete comments, when modifying code, maintain all comments around the code
  • When looking at old codebases, it's best not to delete any empty comments you find

6. Code error handling

6.1 Cause of error

There are many reasons for errors, but they can be roughly divided into the following three types:

  • User error, where a stupid user has roughed up your beloved program, perhaps providing bad input, or doing something absurd
  • The programmer is wrong, the user buttons are all correct, but the program still has a problem, which is caused by the bug in the written code.
  • In an unexpected situation, the user enters ok, and the programmer does not make a mistake, but in an unexpected situation, such as the network is disconnected, the hard disk is full

6.2 Error management report

Error reporting is the dissemination of error information to the client

  • Don't report it, just terminate the program. This is not a good way, but it is simple.
  • Return value judgment, judge whether an error occurs by judging the status code returned by the function return value
  • Exceptions, java uses exceptions to manage errors
  • Signals, are the software equivalent of hardware interrupts, the operating system provides a reasonable error handler for each signal, and c can use signals to handle errors.

6.3 Error Handling

  • log errors
  • The program needs to report errors to the user when there is nothing to do. The user cannot be bombarded with errors all the time, and when there is a recoverable situation, don't report it. Of course there are some errors that only the user can handle and need to be reported to him immediately
  • Sometimes errors can't be resolved on the code side, or you don't know how to solve them, then you need to pass the error upwards

6.4 Error checking

  • Check whether the code has performed resource cleanup, especially the closing of some streams
  • Check the code function parameters, whether they are expected
  • Check function call context state

reference

  1. programming craft

Guess you like

Origin blog.csdn.net/qq_23091073/article/details/131772473