Code specification C# version

1 Purpose of the specification……………………………………………………………… 3

2   Scope of application……………………………………………………………… 3

3   Code comments……………………………………………………………… 3

  3.1 Code comment conventions........................................ 3

  3.2 Module header annotation specifications........................ 3

  3.3 Method annotation specifications........................................ 4

  3.4 Code line comment specifications...................................... 6

  3.5 Variable annotation specifications...................................... 7

4   Naming rules……………………………………………………………… 8

  4.1 Basic naming conventions........................................ 8

  4.2 Basic conventions for various identifier types...................... 9

  4.3 List of component name abbreviations........................ 10

5Other   specifications…………………………………………………… 11

  5.1 Programming style................................................ ... 11

  5.2 Resource release................................................ ... 13

  5.3 Error handling................................................ ... 13

  5.4 Others................................................ ......... 14

1      Normative purpose

  1. In the life cycle of a software, 80% of the cost is maintenance;
  2. Almost no piece of software is maintained by its original developers throughout its life cycle;
  3. Coding standards can improve the readability of software and allow programmers to understand new code as quickly and thoroughly as possible. In order to enforce specifications, every software developer must consistently adhere to coding specifications;
  4. The main reason for using unified coding standards is to standardize the structure and coding style of the application so that the code can be easily read and understood;
  5. Good coding conventions make source code rigorous, readable and meaningful, consistent with other language conventions, and as intuitive as possible.

2      Scope of application

  1. This specification mainly uses C# as the development language specification and is the principle specification of Bao Liang Laboratory;
  2. Since this specification is designed for writing programs, it applies to all work related to writing programs. For each specific project, it may need to be tailored and restocked.
  3. Applicable products: Programs written in C#.

3      code comments

3.1     Code comment conventions

  1. All methods and functions should start with a concise comment describing the function of the code (what the method does). Such descriptions should not include implementation details (how it is done), as this often changes over time, and such descriptions can lead to unnecessary annotation maintenance, or even worse - bad annotations. The code itself and necessary embedded comments will describe the implementation method.
  2. Arguments passed to a procedure should also be described when the function of the argument is not obvious and when the procedure expects the argument to be within a specific range. Function return values ​​and global variables that are changed by procedures, especially those by reference parameters, must also be described at the beginning of each procedure.

3.2      Module header annotation specifications

Everything based on a physical file needs to have module header annotation specifications, for example: .cs file in C#

Description used at the beginning of each module, mainly including: ( Bold words are required parts, the rest are optional)

  1. File Name : The name of this file
  2. Function Description (Description) : Function description and general process description of this module
  3. Data tables (Tables) : Description of the data tables, views, and stored procedures used. If the relationship is complex, it should be explained which tables are erasable and which tables are read-only.
  4. Author : _
  5. Date (Create Date) :
  6. Reference document (optional): the analysis document and design document corresponding to this file.
  7. Reference (Using) (optional): When the developed system refers to Dlls and objects of other systems, the corresponding sources must be listed and whether they are related to the system (if you are not sure, you can leave it blank) to facilitate the creation of installation files.
  8. Revision History : If the owner of the file changes, the name of the person who modified it, the date of modification and the reason for the modification are required.
  9. Separator: *************************** (both before and after)

Examples are as follows:

  

3.3      Method annotation specifications

  1> C# provides a mechanism that allows programmers to document their code using special comment syntax containing XML text. In a source code file, comments in a certain format can be used to instruct a tool to generate XML based on these comments and the source code elements that follow them. In specific applications, classes, interfaces, properties, and methods must have <Summary> sections. In addition, if methods have parameters and return values, they must have <Param> and <Returns> sections. Examples are as follows:

    /// <summary>
    /// …
    /// </summary>
    /// <param name=””></param>
    /// <returns></returns>

  2> Events do not require header annotations, but when they contain complex processing (such as loops/database operations/complex logic, etc.), they should be divided into a single processing function, and the event calls the function.

  3> All methods must add method comments before their definition.

  4> Method comments use the /// format to automatically generate comments in XML tag format.

    An example diagram is as follows:

  

 

  5> The public methods in the public class library need to add the author, date and modification record information after the comments of the general method. They should be annotated in the format of XML tags. The tags are as follows:

<Author>作者</Author>
<CreateDate>建立日期</CreateDate>
<RevisionHistory>    --修改记录
    <ModifyBy>修改作者</ModifyBy>
    <ModifyDate>修改日期</ModifyDate>
    <ModifyReason>修改理由</ModifyReason>

    <ModifyBy>修改作者</ModifyBy>
    <ModifyDate>修改日期</ModifyDate>
    <ModifyReason>修改理由</ModifyReason>

    <ModifyBy>修改作者</ModifyBy>
    <ModifyDate>修改日期</ModifyDate>
    <ModifyReason>修改理由</ModifyReason>
</RevisionHistory>
<LastModifyDate>最后修改日期</LastModifyDate>

  6> If a code file is written by one person, the methods in this code file do not require author information. Non-code file authors must add author, date and other comments when adding methods to this file.

  7> To modify any method, you must add a comment on the modification record.

3.4      Code line comment specifications

  1> If processing a certain function requires many lines of code to implement, and there are many logical structural blocks, comments should be added before the start of the code to explain the processing ideas and precautions for this block of code, etc.

  2> Comments are added on new lines and left aligned with the beginning of the code  

  3> Double slashes and comments are separated by spaces. The example picture is as follows:

  

3.5      Variable annotation specifications

  1> When defining a variable, you need to add a variable comment to explain the purpose of the variable.

  2> Class-level variables should automatically generate comments in XML tag format in the form ///. The example is as follows:       

  3> Method-level variable comments can be placed after the variable declaration statement, left aligned with the comments of the variable declaration in the preceding and following lines, and separated from the code by Tabs.

 

4     Naming rules

4.1      Basic naming conventions

  1> Use a complete English descriptor that can accurately describe the variable/field/class, such as firstName. Simple names can be used for some variables with obvious functions. For example, the incrementing (decreasing) variable in a loop can be named "i".

  2> Try to use terminology in the fields involved in the project.

  3> Use mixed case to improve the readability of the name. To distinguish between multiple words in an identifier, capitalize the first letter of each word in the identifier. Do not use underscores as delimiting characters.

    There are two suitable writing methods for different types of identifiers:

      PasalCasing : The first letter of the identifier is capitalized;

      camelCasing : The first word of the identifier is lowercase.

  4> The following table describes the casing rules for different types of identifiers:

  5> Avoid using abbreviations, and if you must use them, use them with caution. Also, a list of standard abbreviations should be maintained and used consistently.

  6> For common abbreviations, two-letter abbreviations should be in uniform case (example: ioStream, getIOStream); multi-letter abbreviations should have the first letter in uppercase and other letters in lowercase (example: getHtmlTag);

  7> Avoid using long names (preferably no more than 15 letters).

  8> Avoid using names that are similar or differ only in upper and lower case.

4.2      Naming conventions for various identifier types

  1>   Assembly naming

  Laboratory name (Lab) + project name + module name (optional), for example:

    Center server assembly: Lab.SeverCenter;

    Center server business logic assembly: Lab.SeverCenter.Business;

  2>   Namespace naming

  Use the same method as assembly naming: laboratory name (Lab) + project name + module name. In addition, it is generally recommended that the namespace and directory structure be the same. For example:

    Central server: Lab.SeverCenter;

    User control under the central server: Lab.SeverCenter.UserControl;

    Center server business logic: Lab.SeverCenter.Business;

    Center server data access: Lab.SeverCenter.Data;

  3>   Assemblies and DLLs

  l In most cases, an assembly contains all or part of a reusable library contained within a single dynamic link library (DLL).

  l An assembly can be split into multiple DLLs, but this is very rare and not stated in this guideline.

  l Assemblies and DLLs are the physical organization of libraries, while namespaces are logical organizations, and their composition should have nothing to do with the organization of the assembly.

  l Namespaces can, and often do, span multiple assemblies. Consider the following pattern for naming DLLs:

          <Company>.<Component>.dll

          Example: Lab.SeverCenter.dll

  4>  Class and interface naming

  l Class names should use nouns;

  l Avoid using the abbreviation of a word unless its abbreviation is already well known, such as HTTP.

  l The name of the interface must start with the letter I. Ensure that the standard implementation name of the interface only differs by one "I" prefix, for example, the standard implementation of the IComponent interface is Component;

  l Naming of generic type parameters: The name should be T or a descriptive name starting with T, for example:

    public class List<T>

    public class MyClass<Tsession>

  l Avoid duplication of names for classes in different namespaces of the same project. Avoid conflicts and confusion in citations;

  5>  Method naming

  l The first word is usually a verb;

  l If the method returns the value of a member variable, the method name is generally Get + the member variable name. If the returned value is a bool variable, Is is generally used as the prefix. Also, if necessary, consider using attributes instead of methods;

  l If a method modifies the value of a member variable, the method name is generally: Set + member variable name. As above, consider using properties instead of methods.

  6>  Variable naming

  l According to the scope of use, the variables in our code basically have the following types: public variables of the class; private variables of the class (protected and public); parameter variables of the method; local variables used inside the method. The naming rules for these variables are basically the same, see the identifier case comparison table. The differences are as follows:

    a) The public variables of the class are named in the usual way, with no special requirements;

    b) The private variables of the class can be used in two ways: prefixed with "m", such as mWorkerName;

    c) The parameter variable of the method adopts camalString, such as workerName;

  l The local variables inside the method use camalString, such as workerName.

  l Do not use _ or & as the first letter;

  l Try to use short and meaningful words;

  l Single-character variable names are generally only used for variables with very short life spans: i, j, k, m, and n are generally used for integers; c, d, e are generally used for characters; s is used for strings

  l If the variable is a collection, use plural numbers in the variable name. For example, the number of rows in a table should be named: RowsCount;

  l Naming components should use Hungarian nomenclature, and all prefixes should follow the same component name abbreviation list.

4.3   List of component name abbreviations

  The basic principle of abbreviation is to take the first letter of each word in the component class name. If there is only one word, remove the vowels and leave the consonants. Abbreviations are all lowercase.

5     other specifications

5.1 Programming style

  1>   Variable declaration:

  In order to maintain better reading habits, please do not write multiple variable declarations in one line, that is, only declare one variable per line.

  --For example: 
  String strTest1, strTest2; 
  --Should be written as: 
  String strTest1; 
  String strTest2;

  2>    Code indentation:

  l A consistent code indentation style is conducive to the expression of the structural level of the code, making the code easier to read and circulate;

  l Code indentation is implemented using the Tab key. It is best not to use spaces. In order to ensure that the code indentation is consistent on different machines, the width of the Tab key in C# is hereby stipulated to be 4 characters. The setting interface is as follows (Tools - Options):

  l Avoid having more than 5 parameters in the method. Generally, 2 or 3 parameters are appropriate. If it exceeds that, you should use a struct to pass multiple parameters.

  l In order to make it easier to read, please do not make the code line too long. The best width is the screen width (the visible width will be different depending on the display resolution). Please do not exceed the width of the screen you are using. (No more than 80 characters per line of code.)

  l Goto statements should not be used in programs.

  l Always require a default clause in a switch statement to display information.

  l When there are more than 8 method parameters, they are passed in structure or class mode.

  l There is a half-width space left and right of the operator/operator

  l Place the {} numbers of all blocks on one line respectively, and nest them in alignment. Do not put them on the same line. 

  3>     Blank:

  l Blank lines separate logically related code segments to improve readability.

  l You should always use two blank lines in the following situations:

    a) Between two sections of a source file.

    b) Between class declaration and interface declaration.

  l A blank line should always be used in the following situations:

    a) Between two methods.

    b) Between local variables within the method and the first statement of the method.

    c) Before a block comment (see "5.1.1") or a single-line comment (see "5.1.2").

    d) Between two logical sections within a method to improve readability.

  l You should always use spaces in the following situations:

    a) White space should be placed after the comma in the parameter list, such as:

      void UpdateData(int a, int b)

    b) All binary operators, except ".", should be separated from their operands by spaces. There should be no spaces between unary operators and operands, such as: negative sign ("-"), auto-increment ("++") and auto-decrement ("--"). For example:

        a += c + d;

        d++;

    c) The expressions in the for statement should be separated by spaces, for example:

        for (expr1; expr2; expr3)

    d) The forced transformation should be followed by a space, for example:

        char c;

        int a = 1;

        c = (char) a;

5.2      Resource release

  All external resources must be released explicitly. For example: database connection object, IO object, etc.

5.3      Error handling

  1> Don’t “catch the exception but do nothing”. If you hide an exception, you'll never know whether it occurred or not.

  2> When an exception occurs, give a friendly message to the user, but accurately record all possible details of the error, including the time of occurrence, related methods, class names, etc.

  3> Only catch specific exceptions, not general exceptions.

  Correct approach:

  Wrong approach:

5.4      Others

  1> A method only completes one task. Don't combine multiple tasks into a single method, even if those tasks are very small.

  2> Use the unique types of C# instead of the alias types defined in the System namespace.

  3> Don’t use fixed values ​​in your program, use constants instead.

  4> Avoid using many member variables. Declare local variables and pass them to methods. Do not share member variables between methods. If a member variable is shared among several methods, it will be difficult to know which method modified its value when.

  5> Do not declare member variables as public or protected. All are declared as private and use public/protected attributes.

  6> Don’t use specific paths and drive names in your code. Use relative paths and make the paths programmable.

  7> Do some "self-checks" when the application starts and ensure that the required files and attachments are in the specified location. Check the database connection if necessary. Give the user a friendly prompt if any problem occurs.

  8> If the required configuration file cannot be found, the application needs to be able to create one using default values.

  9> If an incorrect value is found in the configuration file, the application should throw an error and give a prompt message to tell the user the correct value.

  10> When selecting the column of DataColumn, use the field name instead of the index number.
    Example: Correct DataColumn["Name"]
          Bad DataColumn[0]

  11> In a class, all field definitions are placed at the head of the class and in front of all methods or attributes.

  12> In a class, all attributes are defined in an attribute block:

Guess you like

Origin blog.csdn.net/HideInTime/article/details/123132849