1. Trang chủ
  2. » Tất cả

Day02 03 standard csharp coding convention

57 2 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Day02 03 Standard CSharp Coding Convention
Trường học Vietnam National University, Hanoi
Chuyên ngành Computer Science
Thể loại Guideline
Năm xuất bản 2005
Thành phố Hanoi
Định dạng
Số trang 57
Dung lượng 574,79 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Cấu trúc

  • 1. INTRODUCTION (5)
    • 1.1. Purpose (5)
    • 1.2. Application scope (5)
    • 1.3. Related documents (5)
  • 2. NAMING CONVENTION (6)
    • 2.1. Capitalization Styles (6)
    • 2.2. Abbreviations (7)
    • 2.3. Namespace Naming Guidelines (8)
    • 2.4. Class Naming Guideline (9)
    • 2.5. ADO.NET Naming class variable (9)
    • 2.6. Interface Naming Guideline (10)
    • 2.7. Attribute Naming Guideline (10)
    • 2.8. Enumeration Type Naming Guideline (11)
    • 2.9. Static Field Naming Guideline (11)
    • 2.10. Parameter Naming Guideline (12)
    • 2.11. Method Naming Guideline (12)
    • 2.12. Property Naming Guideline (13)
    • 2.13. Variable Naming Guideline (14)
    • 2.14. Event Naming Guideline (15)
    • 2.15. Control Naming Standard (17)
    • 2.16. Constant Naming Guideline (19)
  • 3. CODE FORMATS (20)
    • 3.1. Code Comments (20)
    • 3.2. Declarations (25)
    • 3.3. Statements (27)
    • 3.4. White Space (30)
  • 4. LANGUAGE USAGE (31)
    • 4.1. Object Lifecycle (31)
    • 4.2. Control Flow (34)
    • 4.3. Various data types (35)
    • 4.4. Object oriented programming (37)
    • 4.5. Exception Handling (41)
    • 4.6. Delegates and events (44)
    • 4.7. Coding Style (46)
  • 5. PROJECT SETTINGS AND PROJECT STRUCTURE (48)
  • 6. FRAMEWORK SPECIFIC GUIDELINES (51)
    • 6.1. Data Access (51)
    • 6.2. ASP.NET and Web Services (51)
    • 6.3. Serialization (52)
    • 6.4. Remoting (52)
    • 6.5. Security (54)
    • 6.6. Enterprise Services (56)

Nội dung

CSharp Coding Standard S TA N D A R D C S h a r p C o d i n g C o n v e n t i o n Code 09me HD/PM/HDCV/FSOFT Version 1/0 Effective date 20/06/2005 Guideline C Sharp Coding Standard v1/0 09me HD/PM/HDC[.]

Trang 2

Change Description New Version

Trang 3

TABLE OF CONTENTS

Record of change 2

1 INTRODUCTION 5

1.1 Purpose 5

1.2 Application scope 5

1.3 Related documents 5

2 NAMING CONVENTION 6

2.1 Capitalization Styles 6

2.2 Abbreviations 7

2.3 Namespace Naming Guidelines 8

2.4 Class Naming Guideline 9

2.5 ADO.NET Naming class variable 9

2.6 Interface Naming Guideline 10

2.7 Attribute Naming Guideline 10

2.8 Enumeration Type Naming Guideline 11

2.9 Static Field Naming Guideline 11

2.10 Parameter Naming Guideline 12

2.11 Method Naming Guideline 12

2.12 Property Naming Guideline 13

2.13 Variable Naming Guideline 14

2.14 Event Naming Guideline 15

2.15 Control Naming Standard 17

2.16 Constant Naming Guideline 19

3 CODE FORMATS 20

3.1 Code Comments 20

3.2 Declarations 25

3.3 Statements 27

3.4 White Space 30

4 LANGUAGE USAGE 31

4.1 Object Lifecycle 31

4.2 Control Flow 34

4.3 Various data types 35

4.4 Object oriented programming 37

Trang 4

4.5 Exception Handling 41

4.6 Delegates and events 44

4.7 Coding Style 46

5 PROJECT SETTINGS AND PROJECT STRUCTURE 48

6 FRAMEWORK SPECIFIC GUIDELINES 51

6.1 Data Access 51

6.2 ASP.NET and Web Services 51

6.3 Serialization 52

6.4 Remoting 52

6.5 Security 54

6.6 Enterprise Services 56

Trang 5

1 INTRODUCTION

1.1 Purpose

This document requires or recommends certain practices for developing programs in the C# language The objective of this coding standard is to have a positive effect on:

Avoidance of errors/bugs, especially the hard-to-find ones

Maintainability, by promoting some proven design principles

Maintainability, by requiring or recommending a certain unity of style

Performance, by dissuading wasteful practices

Trang 6

BackColor

Camel case

The first letter of an identifier is lowercase and the first letter of each subsequent

concatenated word is capitalized For example:

You might also have to capitalize identifiers to maintain compatibility with existing,

unmanaged symbol schemes, where all uppercase characters are often used for

enumerations and constant values In general, these symbols should not be visible outside

of the assembly that uses them

The following table summarizes the capitalization rules and provides examples for the different types of identifiers

Trang 7

Identifier Case Example

Note: Always ends with the suffix Exception Read-only Static

Note: Always begins with the prefix I

Protected instance

redValue Note: Rarely used A property is preferable to using a protected instance field

Public instance

RedValue Note: Rarely used A property is preferable to using a public instance field

2.2 Abbreviations

To avoid confusion and guarantee cross-language interoperation, follow these rules

regarding the use of abbreviations:

Do not use abbreviations or contractions as parts of identifier names For example, use GetWindow instead of GetWin

Do not use acronyms that are not generally accepted in the computing field

Where appropriate, use well-known acronyms to replace lengthy phrase names For example, use UI for User Interface and OLAP for On-line Analytical Processing

When using acronyms, use Pascal case or camel case for acronyms more than two characters long For example, use HtmlButton or htmlButton However, you should

capitalize acronyms that consist of only two characters, such as System.IO instead of System.Io

Do not use abbreviations in identifiers or parameter names If you must use

abbreviations, use Camel Case for abbreviations that consist of more than two characters, even if this contradicts the standard abbreviation of the word

Trang 8

2.3 Namespace Naming Guidelines

The general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design as follows

.Design suffix For example, the System.Windows.Forms.Design Namespace contains designers and related classes used to design System.Windows.Forms based applications

A nested namespace should have a dependency on types in the containing namespace For example, the classes in the System.Web.UI.Design depend on the classes in

System.Web.UI However, the classes in System.Web.UI do not depend on the classes in

You should use Pascal case for namespaces, and separate logical components with periods,

as in Microsoft.Office.PowerPoint If your brand employs nontraditional casing, follow the casing defined by your brand, even if it deviates from the prescribed Pascal case For example, the namespaces NeXT.WebObjects and ee.cummings illustrate appropriate deviations from the Pascal case rule

Use plural namespace names if it is semantically appropriate For example, use

System.Collections rather than System.Collection Exceptions to this rule are brand names and abbreviations For example, use System.IO rather than System.IOs

Do not use the same name for a namespace and a class For example, do not provide both

a Debug namespace and a Debug class

Finally, note that a namespace name does not have to parallel an assembly name For example, if you name an assembly MyCompany.MyTechnology.dll, it does not have to contain a MyCompany.MyTechnology namespace

Trang 9

2.4 Class Naming Guideline

The following rules outline the guidelines for naming classes:

Use a noun or noun phrase to name a class

Use Pascal case

Use abbreviations sparingly

Do not use a type prefix, such as Cfor class, on a class name For example, use the class name FileStream rather than CFileStream

Do not use the underscore character (_)

Occasionally, it is necessary to provide a class name that begins with the letter I, even though the class is not an interface This is appropriate as long as I is the first letter of an entire word that is a part of the class name For example, the class name IdentityStore is appropriate

Where appropriate, use a compound word to name a derived class The second part of the derived class's name should be the name of the base class For example,

ApplicationException is an appropriate name for a class derived from a class named

Exception, because ApplicationException is a kind of Exception Use reasonable judgment in applying this rule For example, Button is an appropriate name for a class derived from Control Although a button is a kind of control, making Control a part of the class name would lengthen the name unnecessarily

The following are examples of correctly named classes:

public class FileStream

public class Button

public class String

2.5 ADO.NET Naming class variable

Express the name of DataTable variables in the plural form For example, use

Employees rather than Employee

Do not repeat the table name in the column name If the DataTable name is Employee, LastName is preferred over EmployeeLastName The exception is for ID fields

contained in multiple tables, so that that Employees table may contain an EmployeeID field

Trang 10

Do not incorporate the data type in the name of a column If the data type is later changed, and the column name is not changed, the column name would be misleading For example, LastName is preferred over stringLastName

2.6 Interface Naming Guideline

The following rules outline the naming guidelines for interfaces:

Name interfaces with nouns or noun phrases, or adjectives that describe behavior For example, the interface name IComponent uses a descriptive noun The interface name ICustomAttributeProvider uses a noun phrase The name IPersistable uses an adjective Use Pascal case

Use abbreviations sparingly

Prefix interface names with the letter I, to indicate that the type is an interface

Use similar names when you define a class/interface pair where the class is a standard implementation of the interface The names should differ only by the letter I prefix on the interface name

Do not use the underscore character (_)

The following are examples of correctly named interfaces

public interface IServiceProvider

public interface IFormatable

The following code example illustrates how to define the interface IComponent and its standard implementation, the class Component

public interface IComponent

2.7 Attribute Naming Guideline

You should always add the suffix Attribute to custom attribute classes The following is an example of a correctly named attribute class

public class ObsoleteAttribute()

Trang 11

2.8 Enumeration Type Naming Guideline

The enumeration (Enum) value type inherits from the Enum Class The following rules

outline the naming guidelines for enumerations:

Use Pascal case for Enum types and value names

Use abbreviations sparingly

Do not use an Enum suffix on Enum type names

Use a singular name for most Enum types

For example, do not name an enumeration type Protocols but name it Protocol instead Consider the following example in which only one option is allowed

publicenum Protocol

Use a plural name for Enum types that are bit fields

Use a plural name for such enumeration types The following code snippet is a good

example of an enumeration that allows combining multiple options

Always add the FlagsAttribute to a bit field Enum type

2.9 Static Field Naming Guideline

The following rules outline the naming guidelines for static fields:

Use nouns, noun phrases, or abbreviations of nouns to name static fields

Use Pascal case

Do not use a Hungarian notation prefix on static field names

Trang 12

It is recommended that you use static properties instead of public static fields whenever possible

2.10 Parameter Naming Guideline

It is important to carefully follow these parameter naming guidelines because visual design tools that provide context sensitive help and class browsing functionality display method parameter names to users in the designer The following rules outline the naming

guidelines for parameters:

Use camel case for parameter names

Use descriptive parameter names Parameter names should be descriptive enough that the name of the parameter and its type can be used to determine its meaning in most scenarios For example, visual design tools that provide context sensitive help display method parameters to the developer as they type The parameter names should be

descriptive enough in this scenario to allow the developer to supply the correct parameters Use names that describe a parameter's meaning rather than names that describe a parameter's type Development tools should provide meaningful information about a

parameter's type Therefore, a parameter's name can be put to better use by describing meaning Use type-based parameter names sparingly and only where it is appropriate

Do not use reserved parameters Reserved parameters are private parameters that might

be exposed in a future version if they are needed Instead, if more data is needed in a future version of your class library, add a new overload for a method

Do not prefix parameter names with Hungarian type notation

The following are examples of correctly named parameters

type GetType(typeName As string)

string Format(string format, object args())

2.11 Method Naming Guideline

The following rules outline the naming guidelines for methods:

Use verbs or verb phrases to name methods

Use Pascal case

The following are examples of correctly named methods

Trang 13

RemoveAll();

GetCharArray();

Invoke();

2.12 Property Naming Guideline

The following rules outline the naming guidelines for properties:

Use a noun or noun phrase to name properties

Use Pascal case

Do not use Hungarian notation

Consider creating a property with the same name as its underlying type For example, if you declare a property named Color, the type of the property should likewise be Color See the example later in this topic

The following code example illustrates correct property naming

public class SampleClass

Trang 14

public enum Color

In the incorrect example, it is not possible to refer to the members of the Color

enumeration Color.Xxx will be interpreted as accessing a member that first gets the value

of the Color property (type Integer in Visual Basic or type int in C#) and then accesses a member of that value (which would have to be an instance member of System.Int32)

2.13 Variable Naming Guideline

The following rules outline the naming guidelines for properties:

Use a noun or noun phrase to name properties

Use Camel case For primitive type variables, the prefix for variables will be lower-case

Use Hungarian type notation for primitive types

Do not use Hungarian notation for scope of variables

Use objCommand, objConn, param as standard names for SQLCommand and

SQLConnection, SQLParameter objects Use da as name for SqlDataAdapter objects and ds

as name for DataSet objects

Use i, j, k for counting variables

Trang 15

The following code example illustrates correct naming standard for primitive types

C# Style name Common use style name Prefix Example

2.14 Event Naming Guideline

The following rules outline the naming guidelines for events:

Use Pascal case

Do not use Hungarian notation

Use an EventHandler suffix on event handler names Delegates that are used to define an event handler for an event must be suffixed with EventHandler For example, the following declaration is correct for a Close event

public delegate CloseEventHandler(object sender, EventArgs arguments)

Trang 16

Specify two parameters named senderand e The sender parameter represents the object that raised the event The sender parameter is always of type object, even if it is possible to use a more specific type The state associated with the event is encapsulated in

an instance of an event class named e Use an appropriate and specific event class for the

e parameter type

Name an event argument class with the EventArgs suffix

Consider naming events with a verb For example, correctly named event names include

Clicked, Painting, and DroppedDown

Use a gerund (the "ing" form of a verb) to create an event name that expresses the

concept of pre-event, and a past-tense verb to represent post-event For example, a Close

event that can be canceled should have a Closing event and a Closed event Do not use the BeforeXxx/AfterXxx naming pattern

Do not use a prefix or suffix on the event declaration on the type For example, use Close instead of OnClose

In general, you should provide a protected method called OnXxx on types with events that can be overridden in a derived class This method should only have the event

parameter e, because the sender is always the instance of the type

The following example illustrates an event handler with an appropriate name and

parameters

public delegate MouseEventHandler(object sender, MouseEventArgs e ){}

The following example illustrates a correctly named event argument class

Trang 17

public class MouseEventArgs: EventArgs

2.15 Control Naming Standard

Control type Prefix Example

Control (used within procedures when the

specific type is unknown)

Trang 18

Control type Prefix Example

Trang 19

Control type Prefix Example

2.16 Constant Naming Guideline

To clearly distinguish constants from other elements, use all uppercase when naming them

An underscore can be used to separate terms when necessary Example:

Const MIN_QUAL = 25

Trang 20

A blank line to set it apart from the rest of the code should precede a block comment

///

//All rights are reserved Reproduction or transmission in whole

//or in part, in any form or by any means, electronic, mechanical

//or otherwise, is prohibited without the prior written consent

//of the copyright owner

//Filename: PlayloadComponent.cs

///

Single-Line Comments

Short comments can appear on a single line indented to the level of the code that follows

If a comment can't be written in a single line, it should follow the block comment format A single-line comment should be preceded by a blank line Here's an example of a single-line comment in code

Here's an example of a trailing comment in C# code:

Trang 21

Code-Disabling Comments

The // comment delimiter can comment out a complete line or only a partial line disabling comment delimiters are found in the first position of a line of code flush with the left margin Visual Studio NET provides for bulk commenting by selecting the lines of code

Code-to disable and pressing CTRL+K, CTRL+C To uncomment, use the CTRL+K, CTRL+U chord

The following is an example of code-disabling comments:

namespace declaration can be processed as comments and placed in a file

XML documentation is required for classes, delegates, interfaces, events, methods, and properties Include XML documentation for fields that are not immediately obvious

The following sample provides a basic overview of a type that has been documented // XmlSample.cs

/// Longer comments can be associated with a type or member

/// through the remarks tag

Trang 22

private string name;

/// <param name="args">A list of command line arguments.</param>

public static int Main(String[] args)

Trang 23

XML documentation starts with /// When you create a new project, the wizards put some starter /// lines in for you The processing of these comments has some restrictions:

The documentation must be well-formed XML If the XML is not well-formed, a warning is generated and the documentation file will contain a comment saying that an error was encountered

Developers are not free to create their own set of tags

There is a recommended set of tags

Some of the recommended tags have special meanings:

The <param> tag is used to describe parameters If used, the compiler will verify that the parameter exists and that all parameters are described in the documentation If the verification failed, the compiler issues a warning

The cref attribute can be attached to any tag to provide a reference to a code element The compiler will verify that this code element exists If the verification failed, the compiler issues a warning The compiler also respects any using statements when looking for a type described in the cref attribute

The <summary> tag is used by IntelliSense inside Visual Studio to display additional information about a type or member

If you need to give information about a class, interface, variable, or method that isn't appropriate for documentation, use an implementation block comment or single-line comment immediately after the declaration

Document comments must not be positioned inside a method or constructor definition block, because C# associates documentation comments with the first declaration after the comment

Here are the XML documentation tags available:

<c> The <c> tag gives you a way to indicate that text within a description

should be marked as code Use <code> to indicate multiple lines as code

<code> The <code> tag gives you a way to indicate multiple lines as code Use <c>

to indicate that text within a description should be marked as code

<example> The <example> tag lets you specify an example of how to use a method or

other library member Commonly, this would involve use of the <code> tag

<exception> The <exception> tag lets you document an exception class

Compiler verifies syntax

Trang 24

Tag Note

<include> The <include> tag lets you refer to comments in another file that describe

the types and members in your source code This is an alternative to placing documentation comments directly in your source code file

The <include> tag uses the XML XPath syntax Refer to XPath documentation for ways to customize your <include> use Compiler verifies syntax

<list> The <listheader> block is used to define the heading row of either a table

or definition list When defining a table, you only need to supply an entry for term in the heading

Each item in the list is specified with an <item> block When creating a definition list, you will need to specify both term and text However, for a table, bulleted list, or numbered list, you only need to supply an entry for text

A list or table can have as many <item> blocks as needed

<para> The <para> tag is for use inside a tag, such as <remarks> or <returns>,

and lets you add structure to the text

<param> The <param> tag should be used in the comment for a method declaration

to describe one of the parameters for the method Compiler verifies syntax

<paramref> The <paramref> tag gives you a way to indicate that a word is a

parameter

The XML file can be processed to format this parameter in some distinct way

Compiler verifies syntax

<permission> The <permission> tag lets you document the access of a member The

System.Security.PermissionSet lets you specify access to a member

<remarks> The <remarks> tag is where you can specify overview information about a

class or other type <summary> is where you can describe the members of the type

<returns> The <returns> tag should be used in the comment for a method declaration

to describe the return value

<see> The <see> tag lets you specify a link from within text Use <seealso> to

indicate text that you might want to appear in a See Also section Compiler verifies syntax

<seealso> The <seealso> tag lets you specify the text that you might want to appear

in a See Also section Use <see> to specify a link from within text

<summary> The <summary> tag should be used to describe a member for a type Use

<remarks> to supply information about the type itself

<value> The <value> tag lets you describe a property

Comment Tokens - TODO, HACK, UNDONE

When you add comments with comment tokens to your code, you automatically add shortcuts to the Task List window Double-click any comment displayed in the Task List to move the insertion point directly to the line of code where the comment begins

Trang 25

Note: Comments in HTML, CSS, and XML markup are not displayed in the Task List

To add a comment hyperlink to the Task List window, enter the comment marker Enter TODO, HACK, or UNDONE Add the comment text

// TODO Fix this method

// HACK This method works but needs to be redesigned

A hyperlink to your comment will appear in the Task List in the Visual Studio development environment

3.2 Declarations

Number Per Line

One declaration per line is recommended since it encourages commenting In other words, private int level = 2; // indentation level

private int size = 8; // size of table

Placement

Put declarations only at the beginning of blocks (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope

public void SomeMethod()

Trang 26

The one exception to the rule is indexes of forloops, which in C# can be declared in the for statement:

for (int i = 0; i < maxLoops; i++)

{

// Do something

}

Class and Interface Declarations

When coding C# classes and interfaces, the following formatting rules should be followed:

No space between a method name and the parenthesis "(" starting its parameter list

Open brace "{" appears at the beginning of the line following declaration statement and

is indented to the beginning of the declaration

Closing brace "}" starts a line by itself indented to match its corresponding opening statement

For null statements, the "}" should appear immediately after the "{" and both braces should appear on the same line as the declaration with 1 blank space separating the parentheses from the braces:

publicclass Sample : Object

{

private int ivar1;

private int ivar2;

public Sample(int i, int j)

public int Foo

{

get { return this.foo; }

set { this.foo = value; }

Trang 27

Compound statements are statements that contain lists of statements enclosed in braces

“{statements }” See the following sections for examples

The enclosed statements should be indented one more level than the compound

statement

The opening brace should be at the beginning of the line following the line that begins the compound statement and be indented to the beginning of the compound statement The closing brace should begin a line and be indented to the beginning of the compound statement

Braces are used around all statements, even single statements, when they are part of a control structure, such as a if-else or for statement This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces

return (size ? size : defaultSize);

if, if-else, if else-if else Statements

The if-elseclass of statements should have the following form:

Trang 28

Note: if statements always use braces {} Avoid the following error-prone form:

if (condition) //AVOID! THIS OMITS THE BRACES {}!

statement;

for Statements

A forstatement should have the following form:

for (initialization; condition; update)

Ngày đăng: 25/02/2023, 18:04

w