CSharp coding conventions

16 499 0
CSharp coding conventions

Đ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

CSharp coding conventions

C# C ODING C ONVENTIONS 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 C# Coding Conventions Table of Contents INTRODUCTION 0.1 OVERVIEW 0.2 DEFINITIONS, ACRONYMS AND ABBREVIATIONS .5 0.3 REFERENCES ENVIRONMENTAL SETTING VS.NET SETTING FOR TABS 0.4 SOURCE FILES 0.5 SOURCE FILE ORGANIZATION CODE LAYOUT 0.6 LINE LENGTH 0.7 WRAPPING LINES 0.8 USE #REGION TO GROUP MEMBERS 0.9 ONE STATEMENT PER LINE 0.10 INDENTATION AND SPACING 0.11 METHOD DEFINITIONS MUST NOT EXCEED 200 LINES 0.12 INTER-TERM SPACING 0.13 DECLARATION ONLY SOURCE FILES MUST BE AVOIDED .8 COMMENTS 0.14 0.15 0.16 0.17 0.18 0.19 0.20 SINGLE LINE COMMENTS FILE HEADER ROUTINE HEADER REMINDER COMMENTS 10 BLOCK COMMENTS 10 FIXING ERROR COMMENTS 10 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 0.25 0.26 0.27 0.28 0.29 CAPITALIZATION STYLES 11 CAPITALIZATION SUMMARY 11 OBJECT NAMING CONVENTIONS FOR STANDARD OBJECTS 12 OBJECT NAMING CONVENTION FOR DATABASE OBJECTS 13 MENU NAMING CONVENTIONS 14 THIRD-PARTY CONTROLS 14 PROGRAMMING PRACTICES 15 0.30 WRITING METHODS 15 Success Software Service Corp Ltd C# Coding Conventions 0.31 USING STATEMENTS 15 0.32 MISCELLANEOUS PRACTICES 15 Success Software Service Corp Ltd 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] [REC] Rule Recommendation 0.3 References Document Title Capitalization Styles FCGI C# Coding Standards PSV Coding Conventions for CSharp Original Copy http://msdn.microsoft.com/library/default.asp? url=/library/enus/cpgenref/html/cpconcapitalizationstyles.asp C Sharp_Coding_Standards.doc 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 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) + _ * z; // -PREFER var = a * b / (c - g + _ f) + * z // -AVOID Success Software Service Corp Ltd 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 // 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, if ( { // } if ( // } for etc ) PREFER ) { 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); Success Software Service Corp Ltd // CORRECT C# Coding Conventions TestMethod(a,b,c); TestMethod( a, b, c ); // WRONG // WRONG A single space will surround operators, example: a = b; a=b; // CORRECT // 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 // All Rights Reserved // Created by : // Create Date : // Description : Success Software Service Corp Ltd C# Coding Conventions // // Revision History: // // Rev# Date By Description // // //======================================================================== [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 What the sub/function does (not how) List of each external condition such as variables, control, or file that is not obvious List all parameter(s) with brief explanation Parameters are on a separate line with inline comments Explanation of the value returned by function Description of why the exception would be triggered Add caption=”” to the exception tag to name the exception Use this tag to introduce a code use example Use within the tag to detail the example code Attributes include lang=”C#”, title=”” and description=”” Link to another method, class, etc Name of modifier and date performed on a separate line Notes Mandatory If any If any Only use in function If any If any If any If any Notes: With the event function such as cmdOK_Click, Form_Load, the header comment blocks can be unnecessary Success Software Service Corp Ltd C# Coding Conventions 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 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcorixmldocumentation.asp 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; int a; int b; // AVOID // PREFER 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 Class Pascal No AppDomain Const Field Enum Type UPPER Pascal No No Notes Class names must be nouns or noun phrase • Don’t use C prefix (to indicate ‘class’) for class name • PI • ErrorLevel (normal) • SearchOptions (bitwise) Event Pascal No • ValueChange • • Success Software Service Corp Ltd 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 Name event handlers with the EventHandler suffix Use two parameters named 11 C# Coding Conventions sender and e • Suffix with Exception • Exception class Parameter and ProcedureLevel Variables Class-Level Variables GUI Objects Pascal Camel No Yes SystemException recordNumber Camel Yes firstName Camel Yes • Interface Pascal Yes btnCancel txtName IDisposable IEnumerable IComponent Method Pascal No ToString • Name methods with verbs or verb phrases Namespace Property Pascal Pascal No No System.Drawing BackColor • Name properties using nouns or noun phrases Post fix with type name without abbreviations • Prefix with I • Name interfaces with nouns or noun phrases or adjectives describing behavior 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 cbo ComboBox cboCustomer ContextMenu cmu cmuCustomer CrystalReportViewer crv crvCustomer DataGrid dgd dgdCustomer DateTimePicker dtp dtpReportGenerated DomainUpDow dud dudDomain ErrorProvider epr eprCustomer fdg FontDialog 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 Mainmenu MonthCalendar NotifyIcon NumericUpDown OpenFileDialog PageSetUpDialogue Panel PictureBox PrintDialogue PrintDocument PrintPreviewControl PrintPreviewDialogue ProgressBar RadioButton RichTextBox SaveFileDialogue Splitter Statusbar TabControl TextBox Timer Toolbar ToolTip Trackbar TreeView VSScrollBar lvw mnu cal nic nud dlg psd pnl pic pdg pdc ppc ppd prg rad rtb sfd spl sts tab txt tmr tbr tip trk tvw vsb lvwCustomer mnuCustomer calMonthly nicCustomer nudCustomer dlgCustomer psdCustomer PnlCustomer picCustomer pdgCustomer pdcCustomer ppcCustomer ppdCustomer prgCustomer radCustomer rtbCustomer sfdCustomer splCustomer stsCustomer tabCustomer txtCustomer tmrCustomer tbrCustomre tipCustomer trkCustomer tvwCustomer vsbCustomer 0.27 Object Naming Convention for Database Objects [RULE 6.20] This section could be customized depended on the project Name Prefix SqlConnection 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 DataTable Transaction Parameters Crystal ReportDocument Crystal Tables Crystal Table Crystal TableLogOnInfo Crystal ConnectionInfo Crystal Sections Crystal Section Crystal ReportObjects Crystal ReportObject Crystal SubreportObject SqlDataReader OleDbDataReader dc dt trn prm crrpd crtbs crtbl crtli crcnn crscs crsc crros crro rsro drd 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 Help.Contents File.Open Format.Character File.Send.Fax File.Send.Email Menu Handler Name mnuHelpContents mnuFileOpen mnuFormatCharacter mnuFileSendFax 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 cmdm Control Type Command Button Success Software Service Corp Ltd Vendor MicroHelp 14 C# Coding Conventions Programming Practices 0.30 Writing Methods 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 A method should only 'one job' Do not combine more than one job in a single method, even if those jobs are very small Avoid providing functions with many arguments Use struct to wrap arguments 0.31 Using Statements A switch statement must always contain a default branch which handles unexpected cases 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 if Statements Must Not Be Nested More Than 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 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 Do not use ‘magic’ numbers – Don’t use magic numbers, i.e place constant numerical values directly into the source code Exceptions: Values 0, and null can be used safely Magic number is any numeric literal used in your program other than the numbers and 1, and a string literal is any quoted string 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 Self Check - In the application start up, 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 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 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 Use finally Block to Ensure that Resources are Released Suppress Finalization in the Dispose Method - If the calling code calls Dispose, we 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 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 ... Coding Conventions for CSharp Original Copy http://msdn.microsoft.com/library/default.asp? url=/library/enus/cpgenref/html/cpconcapitalizationstyles.asp C Sharp _Coding_ Standards.doc IM-ST CSharp Coding. .. Software Service Corp Ltd C# Coding Conventions 0.31 USING STATEMENTS 15 0.32 MISCELLANEOUS PRACTICES 15 Success Software Service Corp Ltd C# Coding Conventions INTRODUCTION...C# Coding Conventions Revision History Date Version Description Author 12/25/2007 0.1 Initial Draft Hoang Nguyen Success Software Service Corp Ltd C# Coding Conventions Table of

Ngày đăng: 14/01/2014, 14:47

Từ khóa liên quan

Mục lục

  • 0.1 Overview

  • 0.2 Definitions, Acronyms and Abbreviations

  • 0.3 References

  • 0.4 Source Files

  • 0.5 Source File Organization

  • 0.6 Line Length

  • 0.7 Wrapping Lines

  • 0.8 Use #region to Group Members

  • 0.9 One Statement per line

  • 0.10 Indentation and Spacing

    • 0.10.1 Statements Must Use Appropriate Indentation

    • 0.10.2 Blank line

    • 0.10.3 Curly Braces

    • 0.11 Method Definitions Must Not Exceed 200 Lines

    • 0.12 Inter-term Spacing

    • 0.13 Declaration Only Source Files Must Be Avoided

    • 0.14 Single Line Comments

    • 0.15 File Header

    • 0.16 Routine Header

    • 0.17 Reminder Comments

    • 0.18 Block Comments

Tài liệu cùng người dùng

Tài liệu liên quan