Você está na página 1de 27

C# AND

Page 1 of 27

C# AND . NET STANDARDS

STANDARD RELEASE DATE COMPILED BY USED IN PROJECTS

24-08-2001 VIDYA S VISTA

Sonata Software Limited Project ID: VISTA Document name: Coding Guidelines Naming and Coding Conventions Config. ID : Vista_Code_Stds Ok ................... (Prepared by) Date 07/062001 Name VIDYA.S Ok ..................... (Reviewed by) Date 07/062001 Name TEAM Revision History Old Version A B C Current Version A B C D Date Reason for Change Version : D Date: 07/06/2 Ok .................... (Authorized by Date 07/062001 Name ASHA.K.RAO

20/04/01 02/05/01 30/05/01 07/06/01

New issue Changes Incorporated based on feedback Changes Incorporated based on feedback Changes done to UI Stds

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 2 of 27

1. Overview * 2. Naming Conventions * 2.1. Variables * 2.2 C# Specifics 3 2.3. Classes * 2.4. Class Methods * 2.5. Parameter lists * 2.6. Controls and Forms, Web Forms * 2.7. Constants * 2.8. User defined Type Definitions * 2.9. Error Handling * 2.10. Source Files *

3. Coding Conventions * 3.1. Principles * 3.2. Some Specifics * 3.3. Formatting * 3.4. In-Line documentation * 3.5. File Headers * 3.6. Function and Subroutine Headers * 3.7. Type Prefixes *

4. User Interface Guidelines 21

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 3 of 27

1. Overview This document provides an overview of the Coding Guidelines for development using Microsoft .NET. This document describes the Naming Conventions and Coding Conventions that will be followed. MSDN coding guidelines have been followed in preparing this document.

2. Naming Conventions We shall use the Hungarian notation to attach both type and scope information to various object names. The subset we have chosen for our purposes is defined in the following sections. 2.1 Variables Variables can be named like this: <scope><type><MixedCaseName> where <MixedCaseName> is simply the variable name written in mixed case. <scope> is 'pub for Public, pro for Protected, pri for Private, i for Internal, ipro for Internal Protected. Others, app for application variables, sess for session variables. (use above as applicable in VB also. I.e. use pub/pro/pri for global/module/local variables) <type> is int for integer variables, mnu for Menu control objects,

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 4 of 27

udt for user-defined type variables etc. (REFER to Type Prefix table (3.19) for detailed naming of each type Here are some examples : Of local variable definitions: Private priintCounter As Integer Of global variable definitions : Public pubintCounter As Integer Public pubudtThisCell As udtTableEntry

Form and Class properties (unprotected) In object-oriented languages, it is redundant to include class names in the name of class properties, such as Book.BookTitle. Instead, use Book.Title. Functions and Subroutines Public and private functions should be named in MixedCase. Here are some private functions, Private Function GetNextItem () As Integer Private Function GetFullPath (ByVal strFileName As String) As String Private Function GetNextCell () As SCAPITableEntry

Other rules for variable definitions : Use the Imports statement to avoid having to use fully-qualified names for classes unless there is a namespace collision. Do not use public variables. Access to variables should be through the use of Properties (either, Let, Set, Get or Assign). Provide only Get for read-only variables. Append computation qualifiers (Avg, Sum, Min, Max, Index) to the end of a variable name where appropriate. Use complementary pairs in variable

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 5 of 27

names, such as min/max, begin/end, and open/close. Since most names are constructed by concatenating several words, use mixed-case formatting to simplify reading them. In addition, to help distinguish between variables and routines, use Pascal casing (CalculateInvoiceTotal) for routine names where the first letter of each word is capitalized. For variable names, use camel casing (documentFormatType) where the first letter of each word except the first is capitalized. Boolean variable names should contain Is which implies Yes/No or True/False values, such as fileIsFound. Avoid using terms such as Flag when naming status variables, which differ from Boolean variables in that they may have more than two possible values. Instead of documentFlag, use a more descriptive name such as documentFormatType. Even for a short-lived variable that may appear in only a few lines of code, still use a meaningful name. Use singleletter variable names, such as i, or j, for shortloop indexes only.

2.2 C# Specifics The following prefixes should be used for corresponding variables. Structure - struct Enumeration - enum Delegate - del Interface - iface

2.3 Classes Classes can belong to one of the 4 layers Code-behind, Business Faade, Business Rule or Data Access Layer. The names of the classes can be prefixed based on which layer it belongs to : Business Faade Layer BFClassName

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 6 of 27

Business Rules Layer BRClassName Data Access Layer DALClassName

The code-behind class is closely related to the corresponding ASPX page and hence does not have the above convention. For Ex : A class for ChangePassword in Business Faade Layer class for LogIn component will be named as : BFChangePassword within the BFLogIn.dll (Package).

2.4 Class Methods In object-oriented languages, it is redundant to include class names in the name of class properties, such as Book.BookTitle. Instead, use Book.Title. Public Class methods : Public functions and subroutines defined in classes are properties and do not have type prefixes. Protected Class methods : Property Let, Property Set, and Property Get routines do not have type prefixes. Variables of module level should be declared with Private instead of Dim. The module level variables can be differentiated from the local level variables by the use of the Dim statement. In order to access these private variables Let, Get methods should be used. For e.g.: Public Property Get GetCount() As Variant GetCount = intCount

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 7 of 27

End Property Public Property Let GetCount(ByVal vntNewValue As Variant) intCount = Cint(vntNewValue) End Property

2.5 Parameter lists The following can be language specific. VB.Net : Here are some examples: Sub CrackURL (ByVal strURL As String, ByRef strProtcol, _ ByRef strPath, ByRef strPath, ByRef intPort) The parameters should be documented in the procedure header. C# reference value types : For the reference value types in C# listed below, prefix the corresponding parameters as stated : In - in Out - out Ref - ref 2.6 Controls and Forms, Web Forms We shall also use type prefixes when naming controls. Forms are named as if they were controls, although a form name can also act as a class name. For example, we would name a form frmPublication although we could create new instances of the form: Dim frmNewPub As New frmPublication Use meaningful names for naming all controls,pages with mixed-case.

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 8 of 27

All web pages for VISTA should be named as ModuleName_frmName. Ex : Web Page for Change Password would be named as : LogIn_frmChangePassword.aspx. The corresponding Code-Behind class will have the same name. All object controls like Textbox, Buttons on the forms will be named logically with a <type> prefix. Ex : Button on LogIn screen for LogIn will be named as cmdLogin Textbox to enter user-id will be named as txtUserId. 2.7 Constants Constants are named in uppercase letters, with no type or scope prefixes. Arbitrary prefixes can be used to group sets of related constants: Const Const Const Const Const TABLE_SIZE As Integer = 100 DEFAULT_LOG_FILE As String = "log.txt" ERR_GENERIC As Integer = 32767 ERR_LOGON_FAIL As Integer = 32766 ERR_COMPONENT_MISSING As Integer = 32765

2.8 User defined Type Definitions Type names are prefixed with udt. These prefixes are also used as the base-type prefixes when naming instances. The rest of the name is written in mixed case: Type udtTableEntry intNewState As Integer lngAction As Long End Type And in use: Dim udtCell As udtTableEntry 2.9 Error Handling

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 9 of 27

The exception should be identified by a label. This label should have a prefix of err. The name of the procedure should then be appended. err<proc name> . All error handlers should be prefixed with err followed by the name of the error handler. For e.g.: Private Sub Verify() ... ... Catch errVerify as Exception ErrCheckCondition(parameters) End Sub where ErrCheckCondition is a function/sub routine that performs the required validation.

2.10 Source Files Source file naming conventions : For Class source files, follow as per 2.3 Eg : BFChangePassword within BFLogin.DLL For Physical source files, follow as per 2.6 For DLLs should be named as specified in Section 2.3. Eg : BFLogIn.DLL

3. Coding Conventions This section outlines a number of conventions we have found useful when

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 10 of 27

writing code. 3.1 Principles Following are the principles of coding guidelines: Always code for clarity and testability, not efficiency. Choose variable and function names carefully. Be verbose rather than terse, and parenthesize expressions to make them clearer. Write your code for the reader. Limit the scope of constants, variables, functions, and subroutines as much as possible. If you have the choice, always use a local object in preference to a global one. Use explicit type conversions (CInt, CStr, and so on) when assigning between different variable types.

3.2 Some Specifics Follow these guidelines when you write code: 1.Code should not exceed more than 80 char in a single line. 2.Define all variables explicitly. Checking the Require Variable Declaration option under Tools/Options/Editor enforces this. Define variable-length arrays explicitly. (Visual Basic will not enforce this.) 3.Always specify the upper and lower bounds in an array definition. 4.Define constants, and use them in place of numbers in the code. 5.Always use the ByVal and ByRef keywords in parameter lists. Use ByVal wherever you have a choice (For VB.Net and similar languages). 6.Always use the Private keyword on functions and subroutines that are not exported from a module. 7.Do not use implicit type suffixes (such as ! and &) in variable definitions. 8.Variables should be defined only once in the program. If it is defined many times (module level, max value of a list..etc) then it becomes complex to do modifications.

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 11 of 27

9.Instead of the Single data type, double data type should be used since it is more precise. 10.Define the types of all variables and function and subroutine parameters explicitly. For example, use Dim intBufSize As Integer instead of Dim intBufSize, and use Function GetChars (intBufSize As Integer) As Integer instead of Function GetChars (intBufSize). 11.In For loops, use Next <Index> instead of just Next. 12.Code should not be repeated. If same circumstances are repeated then a sub-procedure needs to be generated. Proper commenting indicating duplication of the code has to be provided. 13.If the program sets certain conditions, they need to be checked. If a procedure accepts controls, then it needs to be checked whether the control is of the right type, whose property can be referred. For e.g.: Private Sub Zoom( ctl as Control) ... If Not TypeOf ctl Is PictureBox Then Exit Sub . . . End Sub 14.Objects, which have been assigned to module level variables, should be discharged while exiting the module. For e.g.: Private Sub Form_Load () ... Set frmLogin = New frmLogin End Sub Private Sub Form_Unload () Set frmLogin = Nothing End Sub

15.An object should not be set using the New method

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 12 of 27

but should be explicitly instantiated using the Set method. This ensures that the object will be executed only at the required time and after Set XYZ = Nothing, It cannot be called anymore. Further it also reminds you to set the object to nothing, if it is a module level variable.

16.The GoTo statement should be sparingly used. Its need can be eliminated by using conditional statements (If, Select, Case). An only exception where it can be used though, is the On, Error, Resume statements.

17.Constant length strings should be defined using the Const keyword. For e.g.: Const PORDERIDLEN As Integer = 25 . . . Dim strPOrderId as String * PORDERIDLEN

18.Constant entries in the list of a combo or list box , column headings in the grid should not be entered in the Properties box (which gets activated on pressing F4)of the control. Instead all such properties should be initialized in a separate function at the form level and called from Form_Load or Form_Initialize.

19. Stop and End statements should not be used except for debugging and exiting purposes.

20. Images should not be directly embedded in the Picture property of the control to facilitate future changes. They should be ideally loaded

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 13 of 27

using the LoadPicture or LoadResPicture

21.The base array index can start in either 0 or 1. This can be set by Option Base statement. Usually we set it to 0 which is the default setting.

22.Declare variables together at the top of the function. Each variable can have a short comment on the same line indicating its use if this is not obvious from the name.

23.Testing a String against an empty statement ("" or vbNullString) should always be done with the Len function rather than a string compare. If Len(sName) = 0 Then...

24.Never use = True or = False as part of a conditional. (If fOK = True Then) is redundant. Use string constants if a string appears in more than one place or is visible to the end user. Visible strings may eventually be localized, so using a constant gives a straightforward search-and-replace mechanism for all string usages.

3.3 Formatting Consistent formatting highlights the logical organization of code. The following formatting techniques are recommended: 1.Use the following format (Alignment) for methods:

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 14 of 27

Public Function GetCustomerByNameOrID (_ ByVal CustName As String, _ ByVal CustID As Long _) As ADODC.RecordSet

2. Use four spaces for all indents. Align sections of code using the prescribed indentation. 3. Except for constants, which are best expressed in completely uppercase characters with underscores, use mixed-case instead of underscores to make names easier to read. 4. All If Then structures should be of the multiple line variety and should be followed by End If. Indent code along the lines of logical construction: If ... Then If ... Then ... Else ... End If Else ... End If 5. Use spaces before and after operators.

6. Put a space after each comma in

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 15 of 27

comma-delimited lists such as array values and arguments when doing so does not alter the intent of the code. Exceptions to this rule include: ActiveX Data Object (ADO) Connection argument.

7. Use white space to provide organizational clues to source code. Doing so creates "paragraphs" of code, which aid the reader in comprehending the logical segmentation of the software.

8. Do not use literal numbers or literal strings, such as For i = 1 To 7. Instead, use named constants, such as For i = 1 To NUM_DAYS_IN_WEEK, for ease of maintenance and understanding. General Practices 1. Use variables and routines for one and only one purpose. In addition, avoid creating multi-purpose routines that perform a variety of unrelated functions.

2. Acquire resources as late as possible and release them as soon as possible. As such, you should create objects as late as possible, and destroy them as early as possible to free resources.

3. Every Select-Case statement should include a Case Else condition for trapping

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 16 of 27

unexpected values (actually this should be tested in the preconditions if possible).

4. Use early binding techniques whenever possible.

5. Maintain a tab-width of 4 blanks.

6. Preserve screen real state wherever possible(i.e have only 80 chars of code in each line). For example, when creating a long string, it might be better to build up the string with multiple assignments: Dim strMsg As String strMsg = "This is a paragraph that is to appear " strMsg = strMsg & "in a message box. The text is " strMsg = strMsg & "broken into several lines of code " strMsg = strMsg & "in the source code, making it easier " strMsg = strMsg & "for the programmer to read and debug. " MsgBox strMsg, vbOkOnly, "Text" Dim strQRY as String strQRY = "SELECT Customer.CustomerName, Orders.Ord strQRY = strQRY & "FROM Customer, Orders " strQRY = strQRY & "WHERE Customer.CustomerId = Orde 3.4 In-Line documentation 1. Function headers should be above the signature.

2. One of the best sources of documentation is the code itself. Follow coding format and thoroughly comment your code.

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 17 of 27

By doing this, you are making your program more readable and providing valuable information to yourself and to other programmers who might have to make modifications to the code later. Even assignments and instructions that are not clear should be explained briefly. Private intCounter as Integer 'For no of times user 'attempts login intCounter = ERR_LOGON_FAIL 'No more attempts !

3. Avoid abbreviations, the comment should not be too verbose, or ambiguous. Also it should not describe in explicit what the code is doing, instead the comment should reflect what the code is achieving.

4. End-of-Line Comments End-of-line comments should be used to annotate variable or constant definitions: i. Const MAX_ROWS = 2147483647 ' (2^31)-1 (Max value for long integer) ii. Const ICONIZED = 7 ' For starting up applications

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 18 of 27

' with Shell (). NOTE : End-of-line comments are rarely suitable for annotating code. Hence unwanted inline comments should be removed.

5. Where a function or subroutine contains a number of logical blocks, introduce each block with a separate comment indented to the same level as the code.

6. Use as many lines as necessary, and do not use surrounding ***** lines to delimit comments unless something important is about to happen.

7. Keep comment lines short so that the entire comment can be viewed on a VGA display without scrolling left and right.

8. Use comments to explain the code, not to echo it; if your comments become very involved, consider restructuring the code.

9. Complicated explanations/logic etc can also be moved into the function header.

3.5 File Headers

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 19 of 27

Every module/class should have a header that sits as a comment in the modules definitions area. The header identifies the module and summarizes the external interfaces to it. Here is an example module header: ' ***************************************************** ' Namespace Login ' Module LogIn ' ' Filename aaaa ' ' Author xxxx (Name-of-person) ' Sonata ' Description ' For SignIn/Change Password of a valid user ' ' Revisions : ' 1. 28-02-98, yyyy ' Moved global Session object out of here. ' ' 2. 14-01-99, zzzz ' Added instance checking. ' ****************************************************

3.6 Function annd SubRoutine Header A function header is a comment that describes what the function does a its interface. The description should focus on what or how the function d

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 20 of 27

functions should have function headers, and headers are also recomme event handlers. NOTE : Function headers should be above the signature. Here is an example function header: '--------------------------------------------------------------' Function GetAllTheStuff: ' Retrieve all the available stuff. Don't come home empty handed. ' Returns: ' Total amount of stuff ' Parameters: ' [in] Flags: Attributes ' [out] SomeStuff: Returns valid stuff ' Throws: ' PreConditionException ' PostConditionException ' PreConditions: ' m_CurrentStuff Not Nothing ' PostConditions: ' Stuff cannot be Nothing '---------------------------------------------------------------

3.7 Type Prefixes For ADO Namespace classes,delegates and enumerations, prefix the name with "ADO". For SQL Namespace classes,delegates and

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 21 of 27

enumerations, prefix the name with "SQL". For other System.Data Namespace classes etc, prefix similar to the following stated : DataSet-ds DataRow-dr DataTable-dt TablesCollection-tc

Table A-1 Variables Prefixes Data Type Boolean Byte Currency Date Double File handle (Long) Handle to something (Long) Integer Long Object Single String Variant Window handle (Long) Prefix bln byt cur dtm dbl hf h(... lowercase) int lng obj sng str vnt hwnd

Table A-2 Data Objects: DAO Prefixes

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 22 of 27

Visual Basic Data Type SelBookmarks Container Database Document Dynaset Errors Field Group Index Parameter Property QueryDef Recordset Relation Snapshot Table TableDef User Workspace

Prefix bk cnt db doc dyn err fld grp idx par prop qdef rec rel snap tbl tdef usr wrksp

Table A-3 Controls Prefixes a) System.Winforms Namespace (also for Webforms Namespace where applicable) Class Name Pointer

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 23 of 27

Label TextBox Button LinkButton ImageButton HyperLink DropDownList ListBox DataGrid DataList Repeater CheckBox CheckBoxList RadioButtonList RadioButton Image Panel Calendar AdRotator Table RequiredFieldValidator CompareValidator RangeValidator RegularExpressionValidator CustomValidator ValidationSummary CrystalReportViewer

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 24 of 27

b) System.Data Namespace ClassName Pointer DataSetView SQLConnection DataView DataFormWizard ADOConnection DataSet ADODataSetCommand SQLDataSetCommand

c) System.Components Namespace ClassName Pointer FileSystemWatcher EventLog DirectoryEntry DirectorySearcher MessageQueue PerformanceCounter Process Schedule ServiceController

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 25 of 27

Timer Report

d) System.HTML Namespace (also for Webforms Namespace where applicable) ClassName Pointer Span Button ResetButton SubmitButton TextField TextArea FileField PasswordField CheckBox RadioButton Table LinearLayoutPanel GridLayoutPanel Image ListBox DropDown HorizontalRow

NOTE : Follow similar convention in the other languages

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 26 of 27

(C#,VC++).

4. User Interface Guidelines

1. 2.

Resolution:800 * 600 pixels FONT: Font : Tahoma X-Small - For Web Form objects 10 pts for HTML Forms objects Names/Labels : Bold Entry fields : Regular For Headers of Screens : Tahoma Small or 14 pts, Bold

3.

ALIGNMENT: For HTML Form objects : TEXT : Left NUMERIC : Right

4.

Size of Labels/Textboxes: For Web Form objects : Height : 22 pixels Width : All Labels on a given screen should be of the size of the label with maximum length. For HTML Form objects : Height : 25 pixels Width : All Labels on a given screen should be of the size of the label with maximum length.

5.

Date format:dd/mm/yyyy

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

C# AND

Page 27 of 27

6.

Colors: BackGround Image for all Webform Pages : Vista_backgnd.gif For Labels i.e Field Names : ForeColor : DarkSlateGray For Entry Fields(Like Textboxes) ForeColor : Black Border : Ridge

7.

Document Properties : (WebForm Page Properties) Color : BackGround Color : #EFF7EF Text : #2F4F4F (DarkSlateGray) Link : #996600 Visited Link : #CCCC99 Active Link : #FF0000

8.

Object Naming : (Mandatory) All objects on the screen should be named(ID) as per the conventions listed in this document : For ex : Button for Add : btnAdd

9. All buttons should be Image Buttons (Text Font : Tahoma X-Small/ 10pts)

NOTE : All the above stated are the Guidelines for the User Interface. In case of deviations, especially in Size of the various controls one can use their discretion in order to make the UI comfortable for the user .

file://\\son640\NEW%20QMS\NEW_QMS_SAMPLEPAGES\STDWHITEPAPERS\HT...

9/20/2005

Você também pode gostar