Sunteți pe pagina 1din 9

Design Specifications and Coding Standards

Date: 01-Apr-06
Version: 1.0

1. Objective:

The objective of this document is to enforce consistent style and formatting in developing C#
applications. The primary goal of the document is to have positive effect on

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


 Maintainability, by promoting proven design principles.
 Maintainability, by requiring or recommending a certain unity of style.
 Performance, by dissuading wasteful practices.

2. C# Coding Standards:

2.1) Naming Conversions and Style

1) Use Pascal casing for type and method and constants.

public class SomeClass


{
const int DefaultSize= 100;
public SomeMethod ()
{}
}

2) Use camel casing for local variable names and method arguments.

int number;
void MyMethod (int someNumber)
{}

3) Prefix member variables with m_. Use Pascal casing for the rest of a member
variable name following the m_.

public class SomeClass


{
private int m_Number;
}

4) Name methods using verb-object pair, such as ShowDialog ().

5) Method with return values should have a name describing the value returned, such
as GetObjectState ().

6) Use descriptive variable names


a) Avoid single character variable names, such as i and t. Instead use index or
temp.
b) Do not abbreviate words. (such as num instead of number)

7) Always use C# predefined types rather than the aliases in the System Namespace.

For Example:
object NOT Object.
string NOT String.
int NOT Int32.

8) Use meaningful namespace such as the product name or the company name.

9) Avoid fully qualified type names. Use the using statement instead.

10) Avoid putting a using statement inside a namespace.

11) Group all framework namespaces together and put custom or third-party
namespaces underneath.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MyCompany;
using MyControl;

12) Maintain strict indentation. Do not use Tabs or non standard indentation. Such as
one space. Recommended values are three or four spaces, and the value should be
uniformed across.

13) Indent comment at the same level of indentation as the code you are documenting.

14) All comments should pass spell checking. Misspelled comments indicate sloppy
development.

15) All member variables should be declared at the top, with one line separating them
from the properties or methods.

public class MyClass


{
int m_Number;
string m_Name;

public void SomeMethod1()


{ }
public void SomeMethod2()
{ }
}
16) Declare a local variable as close as possible to its first use.

17) A file name should reflect the class it contains.

18) Always place an open curly ({) in a new line.

2.2) Coding Practices:

1) Avoid putting multiple classes in a single file.

2) A single file should contribute types to only a single namespace. Avoid having multiple
namespaces in the same file.

3) Avoid files with more than 500 lines (Excluding machine-Generated code)

4) Avoid method with more than 25 lines.

5) Avoid methods with more than 5 arguments. Use structures for passing multiple
arguments.

6) Lines should not exceed 80 characters.

7) Do not manually edit any machine generated code.

a) If modifying machine generated code, modify the format and style to match
this coding standard.

b) Use partial classes whenever possible to factor out the maintained portions.

8) Avoid comments that explain the obvious. Code should be self-explanatory. Good code
with readable variables and method names should not require comments.

9) Document only operational assumptions, algorithms insights and so on.

10)Avoid method level documentation.

a) Use extensive external documentation for API documentation.


b) Use method level comments only as tool tips for other developers.

11) With the exception of zero or one, never hard-code a numeric value; always declare a
constant instead.

12) Use the const directive only on natural constants such as the number of days of the
week.

13) Avoid using const on read-only variables. For that, use the readonly directive.
public class MyClass
{
public const int DaysInWeek = 7;
public readonly int Number;
public MyClass(int someValue)
{
Number = someValue;
}
}

14) Every line of code should be walked through in a “white Box” testing manner.

15) Catch only exceptions for which you have explicit handling.

16)In a catch statement that throws an exception, always the original exception( or
another exception constructed from original exception) to maintain the stack location
of the original error:

catch (Exception exception)


{
Messagebox.Show (exception.Message);
throw; //same as throw exception;
}

17) Avoid error code as method return values.

18) Avoid defining custom exception classes.

19) When defining custom exceptions:

a) Derive the custom exception from Exception.


b) Provide custom serialization.

20) Avoid multiple Main () methods in a single assembly.

21) Make only the most necessary types public. Mark other as internal.

22) Avoid friend assemblies. As they increases inter assembly coupling.

23) Avoid code that relies on an assembly that running form a particular location.

24) Minimize code in application assemblies (EXE client assemblies). Use class libraries
instead to contain business logic.

25) Avoid providing explicit values for enums.

//CORRECT
public enum Color
{
Red,Green,Blue
}
//AVOID
public enum Color
{
Red=1,Green=2,Blue=3
}

26) Always use a curly brace scope in an if statement, even if it contains a single
statement.

27) Avoid function calls in Boolean conditional statements. Assign into local variables and
check on them.

bool IsEverythingOK()
{...}

// Avoid
if(IsEverythingOK())
{...}
// Correct
bool ok= IsEverythingOK();
if (ok)
{...}

28) Always use zero based arrays.

29) Always explicitly initialize an array of reference types using a “for“loop.


public class MyClass
{ }
const int ArraySize = 100;
MyClass[] array = new MyClass[ArraySize];
for (int index =0; index< Array.Length; indexer++)
{
Array[index]=new MyClass();
}

30) Do not provide public or protected member variables. Use properties instead.

31) Avoid using “new” inheritance qualifier. Use “override” instead.

32) Never use unsafe code. Except using interop.

33) Always check a delegate for null before invoking it.

34) Classes and Interfaces should have at least 2:1 ratio of methods to properties.

35) Avoid Interfaces with one member. Strive to have three to five members per interface.
Don’t have more than 20 members per interface.12 is probably principle limit.

36) Prefer using explicit interface implementation.

37) Never hardcode strings that might change based on deployment such as connection
strings.

38) Use String. Empty instead of “”.


//Avoid
string name="";

//Correct
string name=string.Empty;

39) When building a long string use “StringBuilder”, not “String”.

40) Don’t use late binding invocation when early-binding is possible.

41) Use application logging and tracing.

42) Never use “go to” unless in a switch statement fall-through.

43) Always have a default case in a switch statement that asserts.

44) Don’t use the “this” reference unless invoking another constructor from within a
constructor.

45) Do not use the base word to access base class members unless you wish to resolve a
conflict with a subclasses member of the same name or when invoking a base class
constructor.

46) Avoid casting to and from “System.Object” in code that uses generics. Use constraints
or the “as” operator instead.

47) Do not define constraints in delegates.

2.3) Error Handling

1) Error handler should be present whenever you anticipate possibility of error.

2) Do not use Try-catch for flow- control.

3) Never declare an empty catch block.

4) Error Message should be user friendly, simple and understandable.

5) Errors should be raised in the routines present in the components and captured in
the application’s GUI.

6) Use Try-Catch statements in each and every function you write. Adhere to it strictly
with out fail.

7) Use dispose on types holding scarce resources, i.e., files, database connections.

8) Refer the “Exception Handling” document for incorporation of exception handling in


the code.
3) ASP.NET

1) Prefix user control names with “uc”

2) The rest of the user control name should be in Pascal Casing (Ex.
ucMyUserControl)

3) Following table illustrates prefixes you need to use for controls in ASP.NET.

Control Name Abbreviations/ Remarks


Prefixes
Form wf,frm
Textbox txt
TextArea txa
Checkbox chk
Check Box List chklst chklstCurrency
Label lbl
Hidden Elements hdn
Combo Box / Drop Down cbo
Button cmd,btn
Submit Button smt
Reset Button rst
Link Button lbtn lbtnSave
Image Button ibtn ibtnExit
Password Field pwd
Radio Button opt
Radio Button List optlst optlstSelect
List Box lst
Frame fra
Image img
Pointer ptr
Panel pan,pnl pnlBackground
Place Holder plh
Calendar cal
Ad Rotator adr
Table tbl tblAppointments
Range Validator rav,rgv
Regular Expression Validator rev
Regular Field Validator rfv
Compare Validator cmv
Custom Validator cuv,csv
Validation Summary vsm
XML Xml XmlDataFile
File Field Fle
Literal Lit
Arraylist Al
Hyperlink hyp
DataGrid dtg,dgr
DataList dtl
Repeater rpt rptReport
Flow Layout Panel flp
Grid Layout Panel glp
Horizontal Rule hr
Crystal Report Viewer crv,crvr crvReport

4) Data Access

1) ANSI SQL 92 standards have to be followed for writing queries.

2) Do not put order by clause in the query unless required.

3) Do not encapsulate readonly database operations in transactions.

4) Use a stored procedure with output parameters instead of single record SELECT
statements when retrieving one row of data.

5) Stored procedure execution is fast when we pass parameters by position (the order
in which the parameters are declared in the stored procedure) rather then by
name.

6) After each data modification statement inside a transaction, check for an error by
testing the global variable @@ERROR

7) Verify the row count when performing DELETE operation

8) Use RETURN statement in stored procedures to help the calling program know
whether the procedure worked properly.

9) Key words should be capital. For example; SELECT, UPDATE, DELETE, INSERT,
FROM, AND WHERE, etc.
10) Do not use “SELECT * FROM” type of query. If all the columns of the table are to be
selected, list all columns in the SELECT in same order as they appear in the table
definition.
11) While writing a query as a string, do not put any space after single quote (‘). There
should be a single space between every two words. There should not be a space
between the last word and the concluding single quote (‘).

12) Where multiple columns are selected, there should be a single space after every ‘,’
between two columns.

13) All the major keywords should come on the new lines

14) The number of columns in a SELECT statement should not be more than 6. The line
separator should be placed in this case after the (,) of the last column of this line
and a single space.

15) For any new line separator, the separator should come after a single space after the
last word of the line.

16) Place a tab after each key word on a new line.