Tải bản đầy đủ (.doc) (16 trang)

CSharp coding conventions

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (209.15 KB, 16 trang )

C# CODING CONVENTIONS
Date: 12/25/2007
Version: 0.1
Status: Reviewing
C# Coding Conventions
Revision History
Date Version Description Author
12/25/2007 0.1
Initial Draft
Hoang Nguyen
Success Software Service Corp. Ltd 2
C# Coding Conventions
Table of Contents
INTRODUCTION 5
0.1 OVERVIEW 5
0.2 DEFINITIONS, ACRONYMS AND ABBREVIATIONS 5
0.3 REFERENCES 5
ENVIRONMENTAL SETTING 5
VS.NET SETTING FOR TABS 5
0.4 SOURCE FILES 6
0.5 SOURCE FILE ORGANIZATION 6
CODE LAYOUT 6
0.6 LINE LENGTH 6
0.7 WRAPPING LINES 6
0.8 USE #REGION TO GROUP MEMBERS 7
0.9 ONE STATEMENT PER LINE 7
0.10 INDENTATION AND SPACING 7
0.11 METHOD DEFINITIONS MUST NOT EXCEED 200 LINES 7
0.12 INTER-TERM SPACING 7
0.13 DECLARATION ONLY SOURCE FILES MUST BE AVOIDED 8
COMMENTS 8


0.14 SINGLE LINE COMMENTS 8
0.15 FILE HEADER 8
0.16 ROUTINE HEADER 9
0.17 REMINDER COMMENTS 10
0.18 BLOCK COMMENTS 10
0.19 FIXING ERROR COMMENTS 10
0.20 SPELLING AND GRAMMAR 10
DECLARATIONS AND INITIALIZATIONS 10
0.21 NUMBER OF DECLARATIONS PER LINE 10
0.22 DECLARATION PRECEDENCE 10
0.23 INITIALIZATION 11
NAMING CONVENTION 11
0.24 CAPITALIZATION STYLES 11
0.25 CAPITALIZATION SUMMARY 11
0.26 OBJECT NAMING CONVENTIONS FOR STANDARD OBJECTS 12
0.27 OBJECT NAMING CONVENTION FOR DATABASE OBJECTS 13
0.28 MENU NAMING CONVENTIONS 14
0.29 THIRD-PARTY CONTROLS 14
PROGRAMMING PRACTICES 15
0.30 WRITING METHODS 15
Success Software Service Corp. Ltd 3
C# Coding Conventions
0.31 USING STATEMENTS 15
0.32 MISCELLANEOUS PRACTICES 15
Success Software Service Corp. Ltd 4
C# Coding Conventions
INTRODUCTION
0.1 Overview
Superior coding techniques and programming practices are hallmarks of a professional programmer.
The bulk of programming consists of making many small choices, which collectively attempt to solve a

large set of problems. A programmer's skill and expertise largely determine the wisdom of those
choices. This document demonstrates how an organization’s C# coding conventions can be enforced
effectively.
0.2 Definitions, Acronyms and Abbreviations
This document provides rules, recommendations, examples for many of the topics discussed.
Rule is the guideline that developers have to follow (mandatory)
Recommendation is the guideline for reference only (optional)
The following typographic conventions are used in this guide:
Example of convention Description
[RULE] Rule
[REC] Recommendation
0.3 References
Document Title Original Copy
Capitalization Styles />url=/library/en-
us/cpgenref/html/cpconcapitalizationstyles.asp
FCGI C# Coding Standards C Sharp_Coding_Standards.doc
PSV Coding Conventions for CSharp IM-ST CSharp Coding Conventions.doc
Environmental Setting
VS.NET Setting for Tabs
[RULE 2.10] Different applications/editors interpret tabs differently. VS.NET provides an option to
insert spaces in place of tabs. Enabling this option will avoid the issues with tabs across the
applications/editors. Use four spaces in places of each tab. Avoid using tabs anywhere in the source
code.
Follow the below step to change the VS.Net settings.
Tools>Option>Text Editor>C#>Tabs – Select Insert Spaces (VS.NET) File Organization
Success Software Service Corp. Ltd 5
C# Coding Conventions
0.4 Source Files
[REC 2.10] File name should match with class name and should be meaningful. This convention
makes things much easier.

[RULE 2.15] Each source file contains a single public class or interface.
[REC 2.15] When private classes and interfaces are associated with a public class, put them in the
same source file as the public class.
0.5 Source File Organization
[RULE 2.20] Source files have the following ordering:
• Beginning comments. See comments and documentation section
• Using directives
• Namespace declaration
• Class and interface declarations
Code Layout
0.6 Line Length
[RULE 3.10] Avoiding lines longer than 120 characters, including space characters for indentation
purpose.
0.7 Wrapping Lines
[RULE 3.15]
When an expression will not fit on a single line, break it according to the below principles:
• Break after a comma or operator
• Prefer higher-level breaks to lower-level breaks.
• Align the new line at the next level of the previous line.
Example of breaking method calls:
LongMethodCall(expr1, expr2, expr3,
expr4, expr5)
Examples of breaking an arithmetic expression.
The first is preferred, since the break occurs outside of the parenthesized expression (higher level
rule).
var = a * b / (c - g + f) + _
4 * z; // PREFER
var = a * b / (c - g + _
f) + 4 * z // AVOID
Success Software Service Corp. Ltd 6

C# Coding Conventions
0.8 Use #region to Group Members
[RULE 3.20] If a class contains a large number of members, attributes, and/or properties, preferably,
separate regions to split-up the private, protected, and internal members, methods , events and
properties . It is also allowed to use the #region construct for separating the smaller auxiliary classes
from the main class.
#region <Name of the region>
// Code goes here
#end region
0.9 One Statement per line
[RULE 3.25] Where appropriate, avoid placing more than one statement per line.
An exception is a loop, such as for (i = 0; i < 100; i++)
0.10 Indentation and Spacing
0.10.1 Statements Must Use Appropriate Indentation
[RULE 3.30] Check to ensure that all statements within methods are properly indented. Use four
white space characters to indent sub blocks of source code.
0.10.2 Blank line
[REC 3.10] Use one blank line to separate logical groups of code.
0.10.3 Curly Braces
[RULE 3.35]
• Curly braces ({}) should be in the same level as the code outside the braces.
• The curly braces should be on a separate line and not in the same line as if, for etc.
if ( )
{
// PREFER
}
if ( ) {
// AVOID
}
0.11 Method Definitions Must Not Exceed 200 Lines

[RULE 3.40] To aid readability of source code, individual method definitions must not exceed 200
source lines.
0.12 Inter-term Spacing
[RULE 3.45] There will be a single space after a comma or a semicolon, example:
TestMethod(a, b, c); // CORRECT
Success Software Service Corp. Ltd 7
C# Coding Conventions
TestMethod(a,b,c); // WRONG
TestMethod( a, b, c ); // WRONG
A single space will surround operators, example:
a = b; // CORRECT
a=b; // WRONG
0.13 Declaration Only Source Files Must Be Avoided
[RULE 3.50] Source files containing declarations only must be avoided. Constants, enums, type
definitions, declare statements and variables etc. are best grouped with the procedures to which they
relate, rather than as part of special "declaration only" source files
Comments
[REC 3.15] The purpose of adding comments to code is to provide a plain English description of what
your code is doing:
• At a higher level of abstraction than the code is doing.
• Talk "What" the code does, not "How" the code works. The comment which shows exactly
how the code works may change as it gets updated or revised.
[RULE 4.10] Use only English for comments.
0.14 Single Line Comments
[RULE 4.15]
• Write inline comments wherever required
• Use // for inline comments
0.15 File Header
[RULE 4.20]
Each file shall contain a header block. The header block must consist of the following

• Copyright statement
• Created By
• Created Date
• Description about the file and Revision History
Example:
//========================================================================
// Copyright <CLIENT NAME>
// All Rights Reserved
// Created by : <AUTHOR>
// Create Date : <MM/DD/YYYY/>
// Description : <Description of the file>
Success Software Service Corp. Ltd 8
C# Coding Conventions
//
// Revision History:
//
// Rev# Date By Description
// 1 <MM/DD/YYYY> <Author> <Summary>
//
//========================================================================
[REC 4.10] The page header can have a TODO: for pending tasks to indicate the pending activities of
the class/file.
0.16 Routine Header
[REC 4.15]
• Use XML tags for documenting types and members.
• All public and protected methods, class definition shall be documented using XML tags.
• XML Tags comments for Types, Fields, Events and Delegates are optional.
• Using these tags will allow IntelliSense to provide useful details while using the types. Also,
automatic documentation generation relies on these tags.
• Standard Routine Header comment block includes the following section headings

Section Heading Comment Description Notes
<summary> What the sub/function does (not how) Mandatory
<remarks> List of each external condition such as variables,
control, or file that is not obvious
If any
<param> List all parameter(s) with brief explanation.
Parameters are on a separate line with inline
comments
If any
<returns> Explanation of the value returned by function Only use in function
<exception> Description of why the exception would be triggered.
Add caption=”” to the exception tag to name the
exception
If any
<example> Use this tag to introduce a code use example If any
<code> Use within the <example> tag to detail the example
code. Attributes include lang=”C#”, title=”” and
description=””
If any
<seealso> Link to another method, class, etc
<modified> Name of modifier and date performed on a separate
line.
If any
Notes:
1. With the event function such as cmdOK_Click, Form_Load, the header comment
blocks can be unnecessary
Success Software Service Corp. Ltd 9
C# Coding Conventions
2. Typing /// in VS.NET just above the method/function will automatically create XML
tags

Refer the below URL for more information about XML style documentation
/>0.17 Reminder Comments
[REC 4.20]
Make use of “TODO” for pending tasks.
Comments beginning 'TODO:” will be treated as reminder comments and should describe the issue
appropriately including the name of the developer responsible for the comment and the date the issue
was identified.
0.18 Block Comments
[REC 4.25] Consider adding comments to in front of major blocks of code, but avoid commenting to
every (or almost every) lines of code.
0.19 Fixing Error Comments
[RULE 4.25] Do not embed any kind of comments about fixing error in the middle code source code.
Instead, for only major error fixes, put those comments to the header comment in the revision history
section.
0.20 Spelling and Grammar
[REC 4.30] Do a spell check on comments and also make sure proper grammar and punctuation is
used.
Declarations and Initializations
0.21 Number of Declarations Per Line
[RULE 5.10] One declaration per line since it encourages commenting.
int a, b; // AVOID
int a; // PREFER
int b;
0.22 Declaration Precedence
[REC 5.10]
The following order is preferred:
• Constants
• Public
• Protected
• Private

Success Software Service Corp. Ltd 10
C# Coding Conventions
Note: All Public constant declarations must appear before private constant declarations within the
declarations section of a source file.
0.23 Initialization
[REC 5.15] Try to initialize local variables where they are declared.
Example:
double width = 1000;
string firstName = ”Doe”;
Naming Convention
0.24 Capitalization Styles
This section explains capitalizations will be used
0.24.1 Pascal Casing
This convention capitalizes the first character of each word (as in TestCounter).
Note: Two-letter abbreviations in Pascal casing have both letters capitalized (Ex: UIEntry)
0.24.2 Camel Casing
This convention capitalizes the first character of each word except the first one. E.g. testCounter.
0.24.3 Upper Case
This convention capitalizes all character of the word. Ex: PI
0.25 Capitalization Summary
[RULE 6.10] Use the following table for naming conventions.
Type
Case Hungarian Example Notes
Class Pascal No AppDomain • Class names must be nouns
or noun phrase.
• Don’t use C prefix (to indicate
‘class’) for class name
Const Field UPPER No PI
Enum Type Pascal No
ErrorLevel (normal)

SearchOptions
(bitwise)
• Use singular names for
enumeration types
• Do not add Enum to the end
of Enum name
• If the Enum represents
bitwise flags, end the name
with a plural
Event Pascal No ValueChange • Name event handlers with the
EventHandler suffix
• Use two parameters named
Success Software Service Corp. Ltd 11
C# Coding Conventions
sender and e
Exception class Pascal No SystemException • Suffix with Exception
Parameter and
Procedure-
Level Variables
Camel Yes recordNumber •
Class-Level
Variables
Camel Yes firstName
GUI Objects Camel Yes btnCancel
txtName
• Post fix with type name
without abbreviations
Interface Pascal Yes IDisposable
IEnumerable
IComponent

• Prefix with I
• Name interfaces with nouns
or noun phrases or adjectives
describing behavior.
Method Pascal No ToString • Name methods with verbs or
verb phrases.
Namespace Pascal No System.Drawing
Property Pascal No BackColor • Name properties using nouns
or noun phrases
0.26 Object Naming Conventions for Standard Objects
[RULE 6.15] This section could be customized depended on the project.
Object Prefix Example
Button btn btnCustomer
CheckBox chk chkCustomer
CheckBoxList chkl chkLCustomer
ColorDialog cdg cdgBox
ComboBox
cbo
cboCustomer
ContextMenu cmu cmuCustomer
CrystalReportViewer crv crvCustomer
DataGrid dgd dgdCustomer
DateTimePicker dtp dtpReportGenerated
DomainUpDow dud dudDomain
ErrorProvider epr eprCustomer
FontDialog
fdg
fdgCustomer
Form frm frmCustomer
GridControl grd grdCustomer

GroupBox grp grpCustomer
HelpProvider hlp hlpCustomer
HScrollBar hsb hsbCustomer
ImageList iml imlCustomer
Label lbl lblCustomer
LinkLabel llbl llblCustomer
ListBox lst lstCustomer
Success Software Service Corp. Ltd 12
C# Coding Conventions
ListView lvw lvwCustomer
Mainmenu mnu mnuCustomer
MonthCalendar cal calMonthly
NotifyIcon nic nicCustomer
NumericUpDown nud nudCustomer
OpenFileDialog dlg dlgCustomer
PageSetUpDialogue psd psdCustomer
Panel pnl PnlCustomer
PictureBox pic picCustomer
PrintDialogue pdg pdgCustomer
PrintDocument pdc pdcCustomer
PrintPreviewControl ppc ppcCustomer
PrintPreviewDialogue ppd ppdCustomer
ProgressBar prg prgCustomer
RadioButton rad radCustomer
RichTextBox rtb rtbCustomer
SaveFileDialogue sfd sfdCustomer
Splitter spl splCustomer
Statusbar sts stsCustomer
TabControl tab tabCustomer
TextBox txt txtCustomer

Timer tmr tmrCustomer
Toolbar tbr tbrCustomre
ToolTip tip tipCustomer
Trackbar trk trkCustomer
TreeView tvw tvwCustomer
VSScrollBar vsb vsbCustomer
0.27 Object Naming Convention for Database Objects
[RULE 6.20] This section could be customized depended on the project.
Name Prefix
SqlConnection con
SqlCommand cmd
SqlParameter prm
ParameterDirection prmd
SqlDataAdapter adp
OleDbConnection
cnn
OleDbCommand cmd
OleDbDataAdapter adp
DataSet ds
DataView dv
DataRow dr
DataRowView drv
Success Software Service Corp. Ltd 13
C# Coding Conventions
DataColumn dc
DataTable dt
Transaction trn
Parameters prm
Crystal ReportDocument crrpd
Crystal Tables crtbs

Crystal Table crtbl
Crystal TableLogOnInfo crtli
Crystal ConnectionInfo crcnn
Crystal Sections crscs
Crystal Section crsc
Crystal ReportObjects crros
Crystal ReportObject crro
Crystal SubreportObject rsro
SqlDataReader drd
OleDbDataReader drd
0.28 Menu Naming Conventions
[RULE 6.25] Applications frequently use an abundance of menu controls. As a result, you need a
different set of naming conventions for these controls. Menu control prefixes should be extended
beyond the initial menu label by adding an additional prefix for each level of nesting, with the final
menu caption at the end of the name string. For example:
Menu Caption Sequence Menu Handler Name
Help.Contents mnuHelpContents
File.Open mnuFileOpen
Format.Character mnuFormatCharacter
File.Send.Fax mnuFileSendFax
File.Send.Email mnuFileSendEmail
When this convention is used, all members of a particular menu group are listed next to each other in
the object drop-down list boxes. In addition, the menu control names clearly document the menu
items to which they are attached.
0.29 Third-party Controls
[REC 6.10] Each third-party control used in an application should be listed in the application's
overview comment section, providing the prefix used for the control, the full name of the control, and
the name of the software vendor:
Prefix Control Type Vendor
cmdm Command Button MicroHelp

Success Software Service Corp. Ltd 14
C# Coding Conventions
Programming Practices
0.30 Writing Methods
1. Method name should tell what it does - Do not use misleading names. If the method name
is obvious, there is no need of documentation explaining what the method does.
2. A method should do only 'one job'. Do not combine more than one job in a single method,
even if those jobs are very small.
3. Avoid providing functions with many arguments. Use struct to wrap arguments
0.31 Using Statements
1. A switch statement must always contain a default branch which handles unexpected
cases.
2. Single Line if Statement Must Not Be Used - In the interest of making source code more
readable, single line if statements are to be avoided.
3. if Statements Must Not Be Nested More Than 3 Levels - To ensure that procedures are
easy to understand, test and maintain, if statements must not be nested beyond three levels
deep.
0.32 Miscellaneous Practices
1. Floating point values shall not be compared using either the == or! = operators - Most
floating point values have no exact binary representation and have a limited precision.
Exception: When a floating point variable is explicitly initialized with a value such as 1.0 or
0.0, and then checked for a change at a later stage.
2. Do not use ‘magic’ numbers – Don’t use magic numbers, i.e. place constant numerical
values directly into the source code. Exceptions: Values 0, 1 and null can be used safely.
Magic number is any numeric literal used in your program other than the numbers 0 and 1,
and a string literal is any quoted string.
3. Minimize the Number of Loops Inside a try Block - Minimize the number of loops inside a
try block, and minimize the number of try blocks inside a loop. A long loop could amplify the
overhead of structured exception handling.
4. Self Check - In the application start up, do some kind of "self check" and ensure all required

files and dependencies are available in the expected locations. Check for database
connection in start up, if required. Give a friendly message to the user in case of any
problems.
5. Default Config Settings - If the required configuration file is not found, application should be
able to create one with default values. If a wrong value found in the configuration file,
Success Software Service Corp. Ltd 15
C# Coding Conventions
application should throw an error or give a message and also should tell the user what are
the correct values.
6. Use validation code to reduce unnecessary exceptions - If we know that specific
avoidable condition can happen, proactively write code to avoid it. For eg, adding validation
checks such as checking for null before using and item from the cache can significantly
increase performance by avoiding exceptions.
7. Use finally Block to Ensure that Resources are Released.
8. Suppress Finalization in the Dispose Method - If the calling code calls Dispose, we
do not want the garbage collector to call a finalizer because the unmanaged
resources will already been returned to the operating system. We must prevent
the garbage collector from calling the finalizer using GC.SuppressFinalization in
our Dispose method.
9. Do not modify or re-organize current source code - Unless required by fixing errors or
reformatting source code to follow this coding convention. Try to keep modifying the current
source as least as possible. This makes comparing different version of source code easier.
10. Be consistent through out the code - For anything that is not enforced by this coding
convention document, developers can use any convention they feel convenient. But no
matter what convention chosen, that should be applied consistently through out the code.
Success Software Service Corp. Ltd 16

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×