C # Coding Specification (reprint)

Source: Internet
Author: User

Original: http://www.cnblogs.com/wulinfeng/archive/2012/08/31/2664720.html

1 The purpose of the specification ... ..... .... ... .... .... ..... ..... ...., ... and ... . ..... .....-....-.....-....-..... 3

2 The scope of application ... ..... ..... ..... ... .. ..... .....-.....-... and ..... ... and ..... .....-......... 3

3 Code comment ... ..... ... .... ... .... ... ..... ..... ..... ..... ..... ... .. .................... 3

3.1 Code Comment Convention ..... ..... ..... ....................... 3

3.2 Module Header annotation specification ....... ..................... 3

3.3 Method Annotation specification ..... ..... ..... ..... ..................... 4

3.4 Code line Comment Specifications ..... ..... ..... ..................... 6

3.5 Variable annotation specification ..... .... ..... ..... ...................... 7

4 Naming rules ... ..... ... .... ... .... ... ..... ..... .... ..... ..... ..... ..... ... .. ..... ..... ......... 8

4.1 The basic convention of naming ...... ..... ...................... 8

4.2 Basic conventions for the various types of identifiers ..... ........... 9

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

5 Other specifications ... ..... ... ... ... ... . ... .... .... ..... .........-... and ..... ... and ..... ...., ..... the ....... One

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

5.2 Release of resources ..... ..... ..... ..... ..... ..................... 13

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

5.4 Other ... ..... .... .... ..... ................................. 14

1 Specification Purpose

    1. In the life cycle of a software, 80% of the cost is maintenance;
    2. Almost no software is maintained by the original developer throughout its lifecycle;
    3. Coding specifications can improve the readability of the software, allowing programmers to understand the new code as quickly and thoroughly as possible. In order to implement the specification, each software developer must conform to the coding specification;
    4. The main reason for using the unified coding specification is to standardize the structure and coding style of the application so that it is easy to read and understand the code;
    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 is mainly based on C # for the development of language norms, for the Baoliang laboratory principle of norms;
    2. Since this specification is designed for writing a program, it is applicable to all work matters relating to the writing of the program. For each specific project, you may need to crop and replenish it.
    3. Applicable personnel: Students majoring in software engineering;
    4. Applicable products: Programs written in C #.

3 code Comments

3.1 Code Comment Conventions

    1. All methods and functions should start with a concise note describing the functionality of the code (what to do). This description should not include details of the execution process (how it is done), as this is often changed over time, and this description leads to unnecessary annotation maintenance work, or even worse-to become the wrong comment. The code itself and the necessary embedded annotations describe the implementation method.
    2. The parameters passed to the procedure should also be described when the function of the parameter is not obvious and when the procedure wants the parameter to be within a specific range. function return values and global variables that are changed by the process, especially those by referencing parameters, must also be described at the beginning of each procedure.

3.2 Module Header Annotation Specification

a Module header annotation specification is required for a physical file as a unit, for example: C # in the . CS file

Instructions for the beginning of each module, mainly include: ( bold is required, the remainder is optional)

    1. file name (file name): The name of this file
    2. function Description (Description): function description and approximate process description for this module
    3. Data Sheet (Tables): A description of the data tables, views, stored procedures used, such as complex relationships, should indicate which are erasable and which tables are read-only.
    4. author (Author):
    5. Date (Create Date):
    6. Reference Document (Reference) (optional): the documentation corresponding to the analysis document, design documents.
    7. Reference (Using) (optional): In the development of the system to refer to other systems DLL, object, to list its corresponding source, whether the system-related ﹙ is not clear can not write ﹚, to facilitate the production of installation files.
    8. Modify a record (Revision history): If the owner of the file changes, then the name of the person to be modified, the date of modification and reasons for modification.
    9. Separator:*************************** (both front and rear)

Examples are as follows:

3.3 Method Annotation Specification

1> C # Provides a mechanism that enables programmers to write documents for their code using special annotation syntax that contains XML text. In a source code file, comments that have a format can be used to instruct a tool to generate XML based on these annotations and the source code elements that follow them. In specific applications, classes, interfaces, properties, methods must have the <Summary> section, in addition to the method if there are parameters and return values, you must have <Param> and <Returns> section. Examples are as follows:

<summary>

...

</summary>

<param name= "" ></param>

<returns></returns>

The 2> event does not require a header annotation, but involves complex processing (e.g., cyclic/database operations/complex logic, etc.), which should be split into a single handler function, and the event is called again.

3> All methods must add a method comment before its definition.

The 4> method annotation automatically generates annotations in the form of XML tags in//.

Mark

Description

Note

<c>

Provides a way to mark text in a description as code

<code>

Provides a way to indicate multiple lines as code

<example>

You can specify examples that use methods or other library members. In general, this will involve the use of <code> tags.

<exception>

A reference to an exception that can be obtained from the current compilation environment.

<include>

A comment in another file that describes the types and members in the source code can be referenced.

<list>

Used to define a header row in a table or definition list.

<para>

Used in tags such as <summary>, <remarks>, or <returns>, allowing you to add structures to text.

<param>

Should be used in comments on method declarations to describe one of the parameters of the method.

<paramref>

Provides a way to indicate that a word is a parameter.

<permission>

The access to the member can be recorded in the document.

<remarks>

Used to add information about a type to supplement the information specified by <summary>.

<returns>

The comment that should be used for the method declaration to describe the return value.

<see>

The link can be specified from within the text.

<seealso>

A reference to a member or field that can be called through the current compilation environment.

<summary>

Should be used to describe a type or type member.

<value>

Properties can be described.

The example diagram is as follows:

5> common methods in the common class library need to add the author, date, and modification record information after the comments of the general method, using the format of the XML tag to raise the label as follows:

<Author></Author> author

<CreateDate></CreateDate> Establishment Date

<RevisionHistory> Modify Records

<ModifyBy></ModifyBy> Modify Author

<ModifyDate></ModifyDate> Date Modified

<ModifyReason></ModifyReason> Reasons for Amendment

<ModifyBy></ModifyBy> Modify Author

<ModifyDate></ModifyDate> Date Modified

<ModifyReason></ModifyReason> Reasons for Amendment

<ModifyBy></ModifyBy> Modify Author

<ModifyDate></ModifyDate> Date Modified

<ModifyReason></ModifyReason> Reasons for Amendment

</RevisionHistory>

<LastModifyDate></LastModifyDate> Last Modified Date

6> A code file is written by one person, the method in this code file does not require author information, and a non-code file author must add a comment such as author, date, and so on when adding a method to this file.

7> Modify any method, you must add a comment that modifies the record.

3.4 Code Line Comment specification

1> if processing a function requires a lot of line code implementation, and there are a lot of logical structure blocks, similar to the code should be added before the beginning of code comments, explain the block code processing ideas and considerations, etc.

2> comment added from new row, align to left of code start

The 3> double slash and comment are separated by a space, as shown in the example diagram:

3.5 Variable Annotation Specification

1> you need to add a variable comment when defining a variable to illustrate the purpose of the variable.

The 2> class-level variable should be annotated in the form of an XML tag that is automatically generated in the///format, as shown in the example below:

A variable comment at the 3> method level can be placed after the variable declaration statement, left-aligned with the comment of the previous row variable declaration, and tab-delimited between the comment and the code.

4 naming rules

4.1 basic conventions for naming

1> to use the full English descriptor that can accurately describe the variable/field/class, such as FirstName. For some of the obvious variables can be a simple name, such as the increment (minus) variable in the loop can be named "I".

2> to use terminology in the areas covered by the project as far as possible.

3> to increase the readability of a name by using a mixed case. To distinguish multiple words in an identifier, capitalize the first letter of each word in the identifier. Do not use underscores for separating characters.

There are two suitable writing methods that fit into different types of identifiers:

pasalcasing : The letter of the first word of an identifier is capitalized;

camelCasing : The letter of the first word of the identifier is lowercase.

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

Identifier

Uppercase and lowercase

Example

Name space

Pascal

Namespace Com.Techstar.ProductionCenter

Type

Pascal

public class Devslist

Interface

Pascal

public interface Itablemodel

Method

Pascal

public void UpdateData ()

Property

Pascal

public int length{...}

Event

Pascal

public event EventHandler Changed;

Private fields

Camel

private string FieldName;

Non-private fields

Pascal

public string FieldName;

Enumeration values

Pascal

Filemode{append}

Parameters

Camel

public void UpdateData (string fieldName)

Local variables

Camel

String FieldName;

5> avoid using abbreviations, and use them sparingly if you must use them. At the same time, you should keep a list of standard abbreviations and be consistent when you use them.

6> for common acronyms, the two-letter abbreviation should be in a uniform case (example: IoStream, Getiostream), a multi-letter abbreviation in uppercase letters, and other lowercase letters (example: Gethtmltag);

7> avoid the use of long names (preferably no more than 15 letters).

8> avoid using names that are similar or differ only in case.

4.2 naming conventions for various identifier types

1> Assembly naming

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

Hub Server assembly: Lab.severcenter;

Hub Server business logic assembly: Lab.SeverCenter.Business;

2> namespace naming

In the same way that the assembly is named: 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 controls under the central server: Lab.SeverCenter.UserControl;

Central server business logic: Lab.SeverCenter.Business;

Central server data access: Lab.SeverCenter.Data;

3> Assemblies and DLLs

In most cases, the assembly contains all or part of the reusable library, and it is contained in a single dynamic-link library (DLL).

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

The assemblies and DLLs are the physical organization of the library, and the namespace is a logical organization, and its composition should be independent of the organization of the Assembly.

L namespaces can and often span multiple assemblies. Consider the following pattern to name the DLL:

<company>.<component>.dll

Example: Lab.SeverCenter.dll

4> class and interface naming

The name of the L class is to be used as a noun;

Avoid using abbreviations for words unless their abbreviations are well known, such as HTTP.

The name of the L interface begins with the letter I. Ensure that the standard implementation of the interface name only one "I" prefix, for example, the standard implementation of the IComponent interface is component;

l Naming of generic type parameters: Name the descriptive name to be T or start with T, for example:

public class List<t>

public class Myclass<tsession>

L Avoid duplicates for classes in different namespaces of the same project. Avoid conflicts and confusion when referencing;

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 typically the get+ member variable name, and if the value returned is a bool variable, it is generally prefixed with IS. In addition, if necessary, consider using attributes to replace the method;

L If the method modifies the value of a member variable, the method name is generally: Set + member variable name. Ibid., consider using attributes instead of methods.

6> variable naming

L according to the scope of use, the variables in our code are basically the following types, the public variables of the class, the private variables of the class (protected and public), the parameter variables of the method, and the local variables used inside the method. The naming conventions for these variables are basically the same, see the identifier case comparison table. The difference is as follows:

A) The public variables of the class are named in the usual way without special requirements;

b) The private variables of the class are available in two ways: by adding "M" prefixes, such as mworkername;

c) The parameter variables of the method are camalstring, such as Workername;

The local variables inside the L method are camalstring, such as Workername.

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

L try to use short and meaningful words;

The variable name of a single character is generally used only for variables with very short lifetimes: i,j,k,m,n is generally used for integer;c,d,e generally used for characters;s for string

L If the variable is a collection, the variable name is used in complex numbers. For example, the number of rows in a table should be named: Rowscount;

L Naming components to use the Hungarian nomenclature, all prefixes should follow the same list of component name abbreviations

4.3 Component name abbreviation list

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

Component type

Abbreviation

Example

Label

Lbl

Lblnote

Textbox

Txt

Txtname

Button

Btn

Btnok

ImageButton

Ib

IbOK

LinkButton

Lb

Lbjump

HyperLink

Hl

Hljump

DropDownList

Ddl

Ddllist

CheckBox

Cb

Cbchoice

CheckBoxList

Cbl

Cblgroup

RadioButton

Rb

Rbchoice

RadioButtonList

Rbl

Rblgroup

Image

Img

Imgbeauty

Panel

Pnl

Pnltree

Treeview

Tv

Tvunit

Webcomtable

Wct

Wctbasic

Imagedatetimeinput

Dti

Dtistart

ComboBox

Cb

Cblist

Myimagebutton

Mib

Mibok

Webcomm.treeview

Tv

Tvunit

Pagebar

Pb

Pbmaster

5 Other Specifications

5.1 Programming Style

1> Variable declaration:

In order to maintain a better reading habit, do not write multiple variable declarations on a single line, that is, one row only declares a variable.

For example:

String StrTest1, StrTest2;

Should be written as:

String StrTest1;

String StrTest2;

2> Code indentation:

L Consistent code indentation style, conducive to the structure of the code level of expression, making the code easier to read and circulate;

L Code indentation using the TAB key, it is best not to use spaces, in order to ensure that the code indentation on different machines consistent, it is stipulated in C # tab width of 4 characters, set the interface as follows (Tools-options):

L AVOID the case of more than 5 parameters in the method, generally 2, 3 is advisable. If it is exceeded, a struct should be used to pass multiple parameters.

To make it easier to read, the line of code should not be too long, the best width is the width of the screen (depending on the display resolution, its visible width is also different). Please do not exceed the width of the screen you are using. (no more than 80 characters per line of code.) )

The goto statement should not be used in the program.

L always want the default clause in the switch statement to display the information.

L Pass a struct or class mode when the method parameter is more than 8

L operator/operator left and right empty a half-width space

L The {} Number of all blocks is placed one line, and nested aligned, not on the same line

3> Blank:

l empty lines are separated by logically related code snippets to improve readability.

I should always use two blank lines in the following situations:

A) between two fragments (section) of a source file.

b) between the class declaration and the interface Declaration.

L The following should always use a blank line:

A) between two methods.

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

c) block annotations (see "5.1.1") or single-line comments (see "5.1.2").

D) between two logical segments within a method to improve readability.

L The following should always use spaces:

A) The blanks should be in the argument list after the comma, such as:

void UpdateData (int a, int b)

b) All two-dollar operators, except ".", should use a space to separate it from the operand. There is no space between the unary operator and the operand, for example: minus sign ("-"), self-increment ("+ +"), and self-decrement ("--"). For example

A + = C + D;

d++;

c) The expression in the For statement should be separated by a space, for example:

for (EXPR1; expr2; expr3)

d) 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 explicitly freed. For example: Database connection object, Io object, and so on.

5.3 Error Handling

1> don't "catch an exception and do nothing". If you hide an exception, you will never know what happened to the exception.

2> When an exception occurs, give a friendly message to the user, but to accurately record all possible details of the error, including the time that occurred, the associated method, the class name, and so on.

3> only catches a specific exception, not a generic exception.

Correct practice:

Error procedure:

5.4 other

1> a method to complete only one task. Do not combine multiple tasks into one method, even if those tasks are very small.

2> uses the unique type of C #, not the alias type defined in the System namespace.

3> do not use fixed values in the program, use constants instead.

4> avoid using many member variables. Declares a local variable and passes it to a method. Do not share member variables among methods. If you share a member variable among several methods, it is difficult to know which method changed its value.

5> do not declare member variables as public or protected. Attributes that are declared as private and that use public/protected

6> does not use the specific path and drive name in the code. Use a relative path and make the path programmable.

7> the application starts with "self-test" and ensures that the required files and attachments are in the specified location. Check the database connection if necessary. There are no problems with a friendly hint to the user.

8> if the desired configuration file cannot be found, the application needs to be able to create a copy of the default value itself.

9> If an error value is found in the configuration file, the application throws an error, giving the prompt message to tell the user the correct value.

10> DataColumn Use the field name when fetching columns, do not use the index number.
Example: Correct datacolumn["Name"]
Bad Datacolumn[0]

11> in a class, the field definition is all uniformly placed in front of the class's head, all methods, or properties.

12> in a class, all properties are defined in one property block:

version:1.0.0

date:2012.8.30

C # Coding Specification (reprint)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.