Make writing a habit together! This is the 10th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Today this article is standing on the shoulders of giants, a summary of the current mainstream development specifications, combined with the characteristics of Go language, as well as their own project experience summed up: explosive liver to share two thousand words Go programming specifications.

More elegant specifications will be updated later.

Naming style

1. [Mandatory] The naming in the code cannot start or end with an underscore or a dollar sign.

Example: _name / __name / $name/name_ / name$/ name__

2. [Mandatory] It is strictly forbidden to mix pinyin and English in the naming of the code, let alone directly use Chinese.

Explanation: Correct English spelling and grammar make it easy for readers to understand and avoid ambiguity.

Note that pure pinyin naming should be avoided.

Example: Internationally used names such as Renminbi/Alibaba/Taobao/Youku/Hangzhou can be regarded as English.

Counterexample: DaZhePromotion [Discounted] / getPingfenByName() [score] / int some variable = 3

 

3. [Mandatory] Use UpperCamelCase for naming common variables, types, interfaces, structures, functions, and member variables of structures.

Example: GolangStruct/UserDO/XmlService/TcpUdpDeal/TaPromotion

Counterexample: Golangstruct/UserDo/XMLService/TCPUDPDeal/TAPromotion

 

4. [Mandatory] Private variables, types, interfaces, structures, functions, parameter names, and local variables should all be in the same lowerCamelCase style, and must follow the hump form.

Example: localValue/getHttpMessage()/inputUserId

 

5. [Mandatory] Constant names use UpperCamelCase style and const declaration to make semantic expression complete and clear, not too long name.

Const StatusOK = 200

 

6. Names of Abstract structures begin with Abstract or Base. Exception class names end with Err. A Test class name starts with Test and ends with the name of the function it is testing.

Example: ParamsErr := errors.New(” params err “)

 

7. Interface naming conventions generally use the end of ER: The interface name of a single function is suffixed with “ER”, and the implementation of the interface removes “ER”. The interface names of the two functions are combined with the names of the two functions, with er as the suffix, and the implementation of the interface removes ER. An interface that abstracts the function of three or more functions, similar to structure naming.

 

8. [Mandatory] Data and slice type names end with Arr, and map type names end with Map. Structures with the same function can have the same end depending on the function. Api requests end with Req and the corresponding end with Res. Data structures end with xxxModel and XXX is the name of the data table.

Var userArr [3]string LoginReq struct{} / type UserDO struct{}

 

9. [Mandatory] Returns a function whose result is mainly Boolean. The function name can start with is or has

10. [Mandatory] All project names should be in lower case and separated by -. The package directory name should be lowercase, and a single word should be used as far as possible. Words should not be separated by symbols. However, if the structure name has plural meanings, the structure name can be plural. The package name (package namepackage) in the package directory, such as a non-main function, is kept in the package directory name and separated by _, and the test file ends with _test.

Example: db-utils/package db_utils/package db_utils_test

Example: the services

 

11. In order to achieve the goal of code self-interpretation, any custom programming element should be named with as complete a combination of words as possible to express its meaning. Counterexample: arbitrary naming of var a int.

 

12. When naming constants and variables, type nouns should be placed at the end of words to improve identification. As shown in specification [8].

Positive example: startTime/startDate Negative example: startedAt/startDt

 

13. If a module, interface, class, or method uses a design pattern, name the pattern.

Note: The design pattern is reflected in the name, which is helpful for readers to quickly understand the architectural design concept.

 

Code format

1. [Mandatory] If the curly braces are empty, write them succinctly as {}. No line breaks or Spaces are required between the curly braces. If it is a non-empty code block: 1) No line break before the opening brace. 2) Line break after opening brace. 3) Line break before close curly brace. 4) Do not wrap code with else after close curly bracket; A line break must be followed by a closing brace indicating termination.

2. [Mandatory] There is no space between the left parenthesis and the character. Similarly, there is no space between the close parenthesis and the character; You need a space before the opening brace. Example: if (space a == b space)

3. [Mandatory] Spaces must be added between reserved words such as if, for, or switch and the parentheses.

4. [Mandatory] A space must be added to the left and right sides of any binocular or ternary operator. Operators include assignment operator =, logical operator &&, addition, subtraction, multiplication and division symbols, etc.

5. [Mandatory] Use TAB to indent and set the width to 4 Spaces

6. [Mandatory] The maximum number of characters in a single line should not exceed 120. If the number of characters exceeds 120, line breaking is required.

  1. The second line is indented one TAB from the first, starting on the third line and not further indented.
  2. The operator ends with the above.
  3. The dot symbol for the method call ends with the above.
  4. When multiple arguments in a method call require line breaks, do so after commas.
  5. Do not wrap a line before parentheses

7. [Mandatory] When defining and passing function parameters, multiple parameters must be followed by a space.

 

Control statements

  1. 【 Mandatory 】 In a switch block, each case does not need to say “break” to terminate, if you want to execute the case sequentially, use “fallthrough”; A switch block must contain a default statement at the end, even if it has no code at all.

  2. [Mandatory] In high concurrency scenarios, avoid using an “equal” decision as a condition for interruption or exit. Note: If the concurrency control is not properly handled, the equivalent judgment is likely to be “broken down”, and the interval judgment condition greater than or less is used instead. Counterexample: when the number of remaining prizes is judged to be equal to 0, the distribution of prizes is terminated, but the number of prizes suddenly becomes negative due to a concurrent processing error. In this case, the activity cannot be terminated.

  3. If condition {… if condition {… if condition {… return obj; } // Then write else business logic code;

    Note: If () is not used… Else if ()… The else… Mode table logical, to avoid subsequent code maintenance difficulties, [mandatory] do not exceed 3 layers.

    Is: More than three layers of the if – else logic code can be used to defend the statement, strategy, state, such as its central defender statements or code logic thinking first failure, abnormal interruption, exit, such as direct return, by method of multiple export, solve the problem of judging code nested branches, that is a reflection of reverse thinking.

 

4. [Reference] Parameter verification is required under the following circumstances:

  1. Methods that are called infrequently.
  2. Methods that are time-consuming to execute. In this case, the parameter verification time is almost negligible, but if the intermediate execution falls back due to parameter errors or errors, the loss is not worth the gain.
  3. Methods that require extremely high stability and availability.
  4. Open release interface for external supply, regardless of RPC/API/HTTP interface.
  5. Sensitive access.

5. [Reference] No parameter verification is required in the following cases:

  1. A method that is most likely to be called through a loop. However, external parameter inspection requirements must be noted in the method description.

  2. The underlying method that is called more frequently. After all, as with pure water filtration at the end of the process, parameter errors are unlikely to be exposed at the bottom. Generally, the DAO layer and the Service layer are deployed in the same application and server, so the verification of DAO parameters can be omitted.

miscellaneous

1. [Mandatory] When using regular expressions, make good use of their precompilation function to effectively speed up regular matching. Re, _ := regexp.compile (“^hel+o”) // Match isMatch := re.matchString (” Hello world “)

2. [Recommended] Clear unnecessary code segments or configuration information in a timely manner. Note: For garbage code or outdated configuration, resolutely clean up, avoid excessive bloated procedures, code redundancy. Example: For code snippets that have been commented out temporarily and may be restored later, it is a uniform rule to use three slashes (///) above the commented code to explain the reason for commenting out the code.

Abnormal log

1. [Force] Use the control flow mechanism to deal with errors by returning an error from a function as an additional return value. If a function has multiple return values, it is customary to return the error value as the last result. If there is only one case of error, the result is usually set to Boolean. A nil value means there are no errors. Res, err := somepkgAction()

2. [Mandatory] For functions that always return successfully, there is no need to return an error.

3. [Mandatory] The first letter of the error message should be lowercase and avoid line breaks

More and more

More elegant specification practices will be updated…

There are no rules, no standards, only in strict accordance with the norms in the team development, in order to avoid the development of fun, maintenance of the crematorium dilemma ~

The last

Thanks for reading and welcome to like, favorites,coin(attention)!!