C # essential tips for code standardization programmers

Source: Internet
Author: User

1. Introduction

This article is a set of development specifications for C # programmer and C # developer.

Developing a C # program following this specification can bring the following benefits:

· Code compilation is consistent,

· Improve code readability and maintainability,

· Code sharing between programmers when a team develops a project

· Easy code review,

This is the first version. It is applicable only to general rules and cannot cover all situations.

2. file organization

2.1 C # source file

The class name or file name should be brief and should not exceed 2000LOC. Separate the code to make the structure clear. Put each class in a separate file and use the class name to name the file name (of course, the extension is. cs ). Such an agreement will make your work easier.

2.2 Directory design

Create a directory for each namespace. (Use MyProject/TestSuite/TestTier as MyProject. testSuite. testTier path, instead of using the namespace name with a dot as the path). This makes it easier to map the namespace to the directory hierarchy.

3. indent

3.1 line feed

When an expression contains more than one row, it is processed according to these general principles:

· Wrap a line after a comma.

· Line feed after the operator.

· Line feed at the top layer rather than at the lower layer.

· The line is aligned with the start position of the expression at the same layer of the previous statement.

Method call line feed example:

LongMethodCall (expr1, expr2,

Expr3, expr4, expr5 );

Arithmetic expression line feed example:

Recommended:

Var = a * B/(c-g + f) +

4 * z;

Bad format-avoid:

Var = a * B/(c-g +

F) + 4 * z;

We recommend that you use the first method, because the line is broken out of the brackets expression (the High-Level LINE folding principle ). Note that you should use a tab to the indent position, and then use a space to the line position. In our example:

> Var = a * B/(c-g + f) +

>... 4 * z;

'>' Indicates a tab, and '.' indicates a space character. (Tabs are left blank with tab indentation ). A good coding habit is to display tabs and space characters in the editor used.

3.2 Blank

There has never been a uniform standard for indentation using spaces. Some people prefer to use two spaces, some prefer to use four spaces, while others prefer to use eight spaces. Some even prefer to use more spaces. A good practice is to use tabs. Tabs have some advantages:

· Everyone can set the indentation level they like.

· It is only one character rather than 2, 4, 8, and so on, so it will reduce the input (even because of automatic indentation, sometimes you have to manually set indentation or cancel settings, and so on ).

· If you want to increase or decrease indentation, you can mark one piece and use the Tab to increase the indentation level, while Shift-Tab to reduce the indentation level. This applies to almost any text editor.

Here, we define tabs as standard indentations.

Do not indent with spaces-use tabs!

4. Notes

4.1 comments

Block annotations should be avoided. We recommend that you use the // annotation as the C # standard statement. If you want to use block annotations, you should use the following style:

/* Line 1

* Line 2

* Line 3

*/

This is because the comments block and the code block can be separated for readers. Although C-style single-line annotations are not recommended, you can still use them. Once this method is used, there should be a broken line after the comment line, because it is hard to see the code with comments in front of the same line:

/* Blah */

Block annotations are useful in rare cases. Block comments are usually used to comment out large code segments.

4.2 single line comment

You should use the // annotation style to "comment out" the Code (shortcut key, Alt + /). It can also be used for comments of code.

When a single line comment is used for code description, it must be indented to the corresponding encoding level. The commented-out code should be commented out in the first line to make it easier to see the commented-out code.

One piece of experience is that the length of comments should not exceed the length of the interpreted code, because it indicates that the code is too complex and has potential bugs.

4.3 file comment

In the. net Framework, Microsoft has introduced a file based on XML annotations. These files are the C # comments of a regular single row containing XML labels. They follow the single-line comment mode:

/// <Summary>

/// This class...

/// </Summary>

Multi-line XML annotations follow this mode:

/// <Exception cref = "BogusException">

/// This exception gets thrown as soon as

/// Bogus flag gets set.

/// </Exception>

To be recognized as an XML comment row, all rows must start with three backslashes. There are two types of labels:

· Description

· Format/reference

The first type includes labels like <summary>, <param> or <exception>. Description items of these documents describing the API elements of a program must be clearly written to facilitate other programmers. As shown in the preceding multi-line annotation example, these labels generally have names or cref attributes. The compiler checks these attributes, so they must be valid and correct. The second type uses labels such as <code>, <list> or <para> to control the layout of the remarks.

Files can be generated using the 'create' menu in the 'file' menu. Files are generated in HTML format.

5. Statement

5.1 declarations per line

We recommend that each row have only one declaration, because it can be easily annotated.

Int level; // indentation level

Int size; // size of table

When declaring a variable, do not place multiple variables or different types of variables in the same row. For example:

Int a, B; // What is 'A '? What does 'B' stand?

The preceding example also shows the non-obvious defect of the variable name. Be clear when naming variables.

5.2 Initialization

Local variables must be initialized once declared. For example:

String name = myObject. Name;

Or

Int val = time. Hours;

Note: If you initialize a dialog, use the using statement:

Using (OpenFileDialog openFileDialog = new OpenFileDialog ()){

...

}

5.3 class and interface declaration

When writing C # classes and interfaces, follow the following formatting rules:

· Do not use spaces between the method name and the parameter list starting with parentheses.

· Start with the braces "{" sign in the next line of the statement.

· End with "}" and match with the corresponding start sign through its indentation.

For example:

Class MySample: MyClass, IMyInterface

{

Int myInt;

Public MySample (int myInt)

{

This. myInt = myInt;

}

Void Inc ()

{

++ MyInt;

}

Void EmptyMethod ()

{

}

}

For the position of a braces, see section 10.1.

6. Statements

6.1 simple statements

Each line should contain only one statement.

6.2 Return Statement

Do not use peripheral parentheses for a return statement. No:

Return (n * (n + 1)/2 );

Use: return n * (n + 1)/2;

6.3 If, if-else, if else-if else statement

If, if-else and if else-if else statements should look like this:

If (condition ){

DoSomething ();

...

}

If (condition ){

DoSomething ();

...

} Else {

DoSomethingOther ();

...

}

If (condition ){

DoSomething ();

...

} Else if (condition ){

DoSomethingOther ();

...

} Else {

DoSomethingOtherAgain ();

...

}

6.4 for/foreach statement

A for statement should be in the following format:

For (int I = 0; I <5; ++ I ){

...

}

Or place a row (consider replacing it with a while statement)

For (initialization; condition; update );

The foreach statement should be shown below:

Foreach (int I in IntList ){

...

}

Note: in a loop, even if there is only one statement, it is usually enclosed by an arc.

6.5 While/do-while statement

A while statement should be written as follows:

While (condition ){

...

}

An empty while statement should be in the following format:

While (condition );

A do-while statement should be in the following format:

Do

{

...

} While (condition );

6.6 Switch statement

A switch statement should be in the following format:

Switch (condition ){

Case:

...

Break;

Case B:

...

Break;

Default:

...

Break;

}

6.7 Try-catch clause

A try-catch statement should follow the following format:

Try {

...

} Catch (Exception ){}

Or

Try {

...

} Catch (Exception e ){

...

}

Or

Try {

...

} Catch (Exception e ){

...

} Finally {

...

}

7. Blank

7.1 blank lines

Empty rows improve readability. They separate the logically associated code blocks. Two lines of space should be used between the following:

· Logical segments of a source file.

· Class and interface definition (each file only defines one class or interface to avoid this situation ).

A space line should always be used between the following:

· Method

· Attributes

· The local variable in a method and its first statement

· The logical segments in a method are used to improve readability. Note that blank rows must be indented because they include a statement, which makes it easier to insert these rows.

7.2 internal space

A comma or a semicolon should be followed by a space, for example:

TestMethod (a, B, c); Do not use: TestMethod (a, B, c)

Or

TestMethod (a, B, c );

Single space-enclosed operator (except the unary operator and non-logical operator), for example:

A = B; // don't use a = B;

For (int I = 0; I <10; ++ I) // don't use for (int I = 0; I <10; ++ I)

// Or

// For (int I = 0; I <10; ++ I)

7.3 table formatting

A logical block of a row should be formatted as a table:

String name = "Mr. Ed ";

Int myValue = 5;

Test aTest = Test. TestYou;

Use spaces for table formatting instead of tabs, because certain tab indentation settings make table formatting look strange.

8. Naming Conventions

8.1 capital format

8.1.1 Pascal Casing

The first letter of each word (like TestCounter) is used to uppercase ).

8.1.2 Camel Casing

The first letter of each word, such as testCounter, must be capitalized except the first word.

8.1.3 full capital case

An identifier consisting of only one or two characters can be fully capitalized. An identifier consisting of three or more characters should be replaced by Pascal. For example:

Public class Math

{

Public const PI =...

Public const E =...

Public const feigenBaumNumber =...

}

8.2 naming guidelines

It is often considered a bad habit for Hungarian to use low-line characters in names and names according to guidelines.

The Hungarian symbol is a set of prefixes and suffixes that are used to map variable types by name. This naming style was widely used in earlier Windows programs, but it is at least not recommended to be removed. If you follow this Guide, it is not allowed to use the Hungarian symbol.

But remember that a good variable name describes semantics without losing its type.

An exception to this rule is GUI encoding. Including the GUI elements like buttons, all fields and variable names should be suffixed with their type names, not abbreviations. For example:

System. Windows. Forms. Button cancelButton;

System. Windows. Forms. TextBox nameTextBox;

8.2.1 class naming guidelines

· The class name must be a noun or a noun phrase.

· For UsePascal information, see 8.1.1

· Do not use any class prefix

8.2.2 interface naming Guidelines

· Use the naming interface of nouns, nouns, phrases, and adjectives that can describe behaviors. (For example, IComponent or IEnumberable)

· Use Pascal (refer to 8.1.1)

· Use I as the name prefix. It should be followed by an upper-case letter (the first letter of the interface name)

8.2.3 enumeration naming guidelines

· Use Pascal to name the enumerated values and type names

· Do not prefix enumeration types and enumerated values

· Use a single name for enumeration

· Use the plural name for the bit field

8.2.4 read-only and constant naming

· Use nouns, noun phrases, or abbreviations to name static Fields

· Pascal usage (refer to 8.1.1)

8.2.5 parameter/extraordinary Domain Name

· Descriptive names must be used to indicate the meaning and type of a variable. But a good name should be based on the parameter meaning.

· Use of Camel (refer to 8.1.2)

8.2.6 variable naming

· Counting variables are more suitable for I, j, k, l, m, and n when used in trivial counting cycles. (Refer to section 10.2 for more intelligent names of global counts )-

· Use of Camel (refer to 8.1.2)

8.2.7 method naming

· Use the verb or verb phrase naming method.

· Use Pascal (refer to 8.1.2)

8.2.8 attribute naming

· Naming attributes using nouns or phrases

· Pascal usage (refer to 8.1.2)

· Consider naming an attribute with the same name as its type

8.2.9 event naming

· Name the event processor with the suffix of the event Processor

· Use sender and e to name two parameters

· Pascal usage (refer to 8.1.1)

· Use EventArgs suffix to name event parameters

· Use the present and past tense to name the event names with prefix and replication concepts.

· Consider naming events with a verb.

8.2.10 capital Summary

 

Type

 

Case

 

Notes

 

Class/Struct

 

Pascal Casing

 

 

 

Interface

 

Pascal Casing

 

Starts with I

 

Enum values

 

Pascal Casing

 

 

 

Enum type

 

Pascal Casing

 

 

 

Events

 

Pascal Casing

 

 

 

Exception class

 

Pascal Casing

 

End with Exception

 

Public Fields

 

Pascal Casing

 

 

 

Methods

 

Pascal Casing

 

 

 

Namespace

 

Pascal Casing

 

 

 

Property

 

Pascal Casing

 

 

 

Protected/private Fields

 

Camel Casing

 

 

 

Parameters

 

Camel Casing

 

 

 

9. Programming habits

9.1 visibility

Do not make public instances or class variables private. For private members, it is best not to use "private" as a modifier to write nothing. Private is the default situation. Every C # programmer should know this.

Use attribute instead. You can use public static (or constant) to make this rule an exception, so it should not be a rule.

9.2 No Phantom

Do not use magic numbers, that is, using constant values directly in the source code. Replace the latter to prevent changes (for example, your application can process 3540 users instead of 427 your code in 50 lines by dispersing 25000LOC) is wrong and there is no benefit. Declare a constant with numbers to replace:

Public class MyMath

{

Public const double PI = 3. 14159...

}

10. Encoding example

10.1 Brace placement example

Namespace ShowMeTheBracket

{

Public enum Test {

TestMe,

TestYou

}

Public class tew.eclass

{

Test test;

Public Test {

Get {

Return test;

}

Set {

Test = value;

}

}

Void DoSomething ()

{

If (test = Test. TestMe ){

//... Stuff gets done

} Else {

//... Other stuff gets done

}

}

}

}

The Arc should start with a new line in the following cases:

· Namespace Declaration (note that this is newly added in version 0.3 and version 0.2 is different)

· Class/interface/structure Declaration

· Method declaration

10.2 variable naming example

Replace:

For (int I = 1; I <num; ++ I ){

MeetsCriteria [I] = true;

}

For (int I = 2; I <num/2; ++ I ){

Int j = I + I;

While (j <= num ){

MeetsCriteria [j] = false;

J + = I;

}

}

For (int I = 0; I <num; ++ I ){

If (meetsCriteria [I]) {

Console. WriteLine (I + "meets criteria ");

}

}

Try intelligent naming:

For (int primeCandidate = 1; primeCandidate <num; ++ primeCandidate)

{

IsPrime [primeCandidate] = true;

}

For (int factor = 2; factor <num/2; ++ factor ){

Int factorableNumber = factor + factor;

While (factorableNumber <= num ){

IsPrime [factorableNumber] = false;

FactorableNumber + = factor;

}

}

For (int primeCandidate = 0; primeCandidate <num; ++ primeCandidate)

{

If (isPrime [primeCandidate]) {

Console. WriteLine (primeCandidate + "is prime .");

}

}

Note: Index variables are usually called I, j, k, and so on. But Note: Indexer variables generally shoshould be called I, j, k etc. But in case of such, it makes more sense to reconsider this principle. Generally, when the same counter or indexer is reused, give them meaningful names.

Related Article

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.