Introduction to high-quality programming and code specifications

What is high-quality: The code written can achieve the goal of being correct, reliable, concise and clear, which can be called high-quality code

  • Whether the various boundary conditions are considered complete
  • Abnormal situation handling, stability guarantee
  • Easy to read and maintain

Programming principles:

  • simplicity
    • Eliminate "redundant complexity" and write code with simple and clear logic
    • 'Code not understood cannot be fixed and improved
  • readability
    • Code is written for humans, not machines
    • The first step in writing maintainable code is making sure the code is readable
  • productive forces
    • The overall productivity of the team is very important

Coding Standards:

  • Code formatting is as uniform as possible

    • It is recommended to use gofmt to automatically format code
  • Comments (good code has a lot of comments, bad code needs a lot of comments, should provide some context for using the code )

    • What the annotation should do:
      1. Annotate what should be annotated
      2. Comments should explain the code, how it does it
      3. Comments should explain why the code is implemented, properly explain external factors to the code, provide additional context
      4. Comments should explain when the code might go wrong, explain the constraints of the code
    • Public symbols are always commented
      1. Every public symbol declared in the package: variables, constants, functions, and structures needs to be annotated
      2. Any public functions that are neither obvious nor short must be commented
      3. Annotate any function in the library, regardless of length or complexity
      4. With one exception, methods implementing an interface do not need to be annotated
  • Naming conventions (the core goal is to reduce the cost of reading code, focusing on contextual information)

    • concise is better than verbose
    • Acronyms are all uppercase, but when they start a variable and do not need to be exported, use all lowercase
      1. Utilize ServeHTTP instead of ServeHttp
      2. Use XMLHTTPRequest or xmlHTTPRequest
    • The farther the variable is from the place where it is used, the more contextual information needs to be carried. The parameter name can represent some characteristic meanings, know its meaning
    • Function name:
      1. The function name does not carry the context information of the package name, because the package name and function name always appear in pairs
      2. Keep function names as short as possible
      3. When a function in package named foo returns type Foo, type information can be omitted without causing ambiguity
      4. When a function in the package named foo returns type T, type information can be added to the function
    • Package names:
      1. Consists of lowercase letters only. Does not contain uppercase letters or underscores, etc.
      2. be short and contain some contextual information
      3. Do not duplicate the name of the standard library
  • control flow

    • Avoid nesting and maintain normal flow

    • Try to keep normal code paths with minimal indentation. Prioritize error cases or special cases and return as early as possible

    • Most of the failure problems occur in complex conditional statements and loop nesting

      // Bad
      func OneFunc() error{
              
              
      	err:= doSomething()
      	if err == nil{
              
              
      		err := doAnoterThing()
      		if err == nil{
              
              
      			return nil
      		}
      		return err
      	}
      	return err	
      }
      // 进行改进
      func OneFunc() error{
              
              
          if err := doSomething(); err != nil{
              
              
              return err
          }
          if err := doAnotherthing(); err != nil{
              
              
              return err
          }
          return
      }
      
  • Error and exception handling

    • A simple error is an error that occurs only once and does not need to be caught elsewhere

    • Prefer using errors.New to create anonymous variables to directly represent simple errors

    • If required by formatting, use fmt.Error

      func defaultCheckRedirect(req *Request, via []*Request) error {
              
              
      	if len(via) >= 10 {
              
              
      		return errors.New("stopped after 10 redirects")
      	}
      	return nil
      }
      
    • Wrong Wrap and Unwrap

      1. The wrong wrap actually provides the ability of an error to nest another error, thus generating a tracking chain of the error

      2. Use the: %w keyword in fmt.Errorf to associate an error with another error

        list, _, err := c.GEtBytes(cache.Subkey(a.actionID,"srcfiles"))
        if err != nil{
                  
                  
            return fmt.Errorf("reading srcfiles list: w%",err)
        }
        
    • To determine whether an error is a specified error, use errors.Is, which is different from ==, this method can determine whether the error chain contains the error

      if errors.Is(err,fs.ErrNotExist){
              
              
          return true,nil
      }
      
    • To get a specific kind of error on the error chain, use errors.As

      if errors.As(err,fs.pathError)
      
    • panic

      1. It is not recommended to use your panic in business. If it appears, it means that the business has basically collapsed. It is used for real exceptions
      2. If there is a problem that can be blocked or resolved, it is recommended to use error instead of panic
      3. Calling without recover will cause the program to crash
    • recover

      1. recover can only be used in defer functions
      2. Nesting cannot be invalidated
      3. It can only take effect in the defer function in gotuntine
      4. The defer statement will be called before the function returns, and multiple defer statements are last-in-first-out

Guess you like

Origin blog.csdn.net/weixin_68798281/article/details/131997041