Saturday, May 31, 2008

Coding Standards for .Net

General Development Standards :

1). Promote Code Reusability & Eliminate Code Redundancy

As a Dotnet Developer the first thing We should not forget about the basic advantage of the .Net is “Reusability”.

Whenever possible if the work you’re doing can be made generic to the application or the company, it should be developed into a user control or server control so that it doesn’t have to be developed twice.

An example of this would be a date picker for a web application, a control like this should be made reusable for everyone at CAT. Repetitive parts of an application can be turned into a user control and reused throughout the application so that it doesn’t have to be redeveloped and maintenance and changes are easier to make. If you find yourself needing to do the same thing as an existing block of code, just with a slight variation, do not copy and paste the old code and then just change a few lines. Instead, try to think how you can modify the existing code to make it more general. Or factor out the common code into a “helper” that both your new module and the other module can use.

Note: We are planning to have a mutual place on Web where we all can post the reusable code ( Datetime Pickers, Mailing components, Gridcontrolworks, any third party controls, user controls…etc where each person can login & upload the code over there) into that & each and every person use it for further references…

I feel instead of taking code from somewhere else in the Google, hop this can help us in reusing more fastly , since we are not sure that downloaded code from different sites can may or may not work.. So better to go with our local copy..

..Any suggestions on above can be appreciated


2).Write easy-to-understand code (and comment it.. if necessary)

This is very basic experience we face. We use x , y , z etc.. as variables & we use them in throw out the project.. no one other than the coder know what stands for that ‘x’…. Some times lot of searching might be required to search for what is this “x”.. & sometimes the coder itself’s forgets what that x stands for… This was my personal Experience… I observe & some time I do follow in coding for urgency things.. it is wrong.

What you write once will need to be read many times by many people so please use a clear and consistent style. Document all of your code classes, methods, and properties using Comments so that others can have documentation to follow in your foot steps and so that we can read these comments. Make sure your code formatting follows our documented formatting and that you have inline comments explaining assumptions, unobvious things, or work around.

3).Please give a meaning full name to the Variables so that it can easily recognised where ever it is Required to Call., never mention x, y, z, i..etc

Always choose meaningful and specific name whgich resembles the variable.


1) Try to prefix Boolean variables and properties with “Can”, “Is” or “Has”.
2). Avoid using abbreviations unless the full name is excessive.
3). Avoid abbreviations longer than 5 characters.
4). Do not use single character names such as i or j. Use index or counter instead.


.NET Naming Conventions

4) Hungarian Notation

Do not use Hungarian notation in naming variables. Hungarian notation uses different prefixes to embed the variable “type” into the variable name.

Examples: strName, intValue (it is Wrong)

An exception to this is control names. We use Hungarian Notation for these:
Button – btn Label – lbl
CheckBox – chk LinkLabel – lnk
CheckedListBox – chkl Listbox – lst
ComboBox – cbo ProgressBar – pba
Control – ctrl RadioButton – rad
Menus – mnu RichTextBox – rtb
Panel – pnl Splitter – spl
PictureBox – pic StatusBar – sba
Datagrid – dgr TextBox – txt
DatagridColumn – dgrc ToolBar – tba
Dialog Controls – dlg ToolTip – tip
Form – frm
GroupBox – gbx


Camel Case

“Camel case” is the practice of writing identifiers in which no underscores are used to separate words, the first letter is lowercase, and the first letter of each subsequent word is capitalized. Examples: filename, voterAddress. Use camel case to name private and protected fields, parameters, and local variables.

Pascal Case

In “Pascal case”, no underscores are used to separate words, and the first letter of each word is capitalized. Examples: GetFileName, MainForm. Use Pascal case for public fields and properties, class names (including enumerated types and structures), and namespaces.




Naming Constants

All constants should be named in uppercase with underscores to separate words.
Examples: ROW_COUNT, COLUMN_NAME, URL
.NET Coding Standards

USE of USING Keyword of C# :
While reviewing some C# code written by one of my friend, I noticed a lack of calling Dispose() on SqlConnection and SqlCommand objects. And in all cases, the database code was not placed in try / finally blocks. This is typical newbie style of development that everyone, including myself, attempted in the very beginning.
SqlConnection cn = new SqlConnection(connectionString);
SqlCommand cm = new SqlCommand(commandString, cn);
cn.Open();
cm.ExecuteNonQuery();
cn.Close();

It sure is easy to follow :)
The problem is that SqlConnection and SqlCommand implement IDisposable, which means they could have unmanaged resources to cleanup and it is our job, the developers, to make sure Dispose() gets called on these classes after we are finished with them. And, because an exception could be raised if the database is unavailable ( a very real possibility on WebHost4Life :) ), we need to make sure Dispose() gets called even in the case of an exception.
Personally, I like the “using” keyword in C#. Internally, this bad boy generates a try / finally around the object being allocated and calls Dispose() for you. It saves you the hassle of manually creating the try / finally block and calling Dispose().
The new code would looking something like this:
using (SqlConnection cn = new SqlConnection(connectionString))
{
using (SqlCommand cm = new SqlCommand(commandString, cn))
{
cn.Open();
cm.ExecuteNonQuery();
}
}
This is essentially equivalent to the following, although my guess is that C# will internally generate two try / finally blocks (one for the SqlConnection and one for the SqlCommand), but you get the idea:

SqlConnection cn = null;
SqlCommand cm = null;
try
{
cn = new SqlConnection(connectionString);
cm = new SqlCommand(commandString, cn);
cn.Open();
cm.ExecuteNonQuery();
}
finally
{
if (null != cm);
cm.Dispose();
if (null != cn)
cn.Dispose();
}
You may notice the lack of calling Close() on the SqlConnection class, cn. Internally, Dispose() checks the status of the connection and closes it for you. Therefore, technically you don't need to call Close() on the connection (cn) as Dispose() will do it for you. However, I don't think there is any penalty for calling Close() directly and then Dispose(), but I don't know for sure. I doubt it.
In addition, Dispose() destroys the connection string of the SqlConnection class. Therefore, if you want to re-open the connection after calling Dispose() on cn, you will have to re-establish the connection string. Not doing so will throw an exception.


Let me know any questions if you have any in the above usage of USING Scenario…


Comparing Values

Favor a Select Case block instead of an If statement when testing the same variable against four or more values.

For Loops

Do not declare variables outside of a For loop when their only purpose is to iterate through the loop.

Wrong:

VB.NET

Dim currIdx as integer
For currIdx = 0 to 100
‘do something
Next

C#

int i;
for(i = 0; i <= 100; i++;) { Value += “A”; } Correct: VB.NET For currIdx as integer = 0 to 100 ‘do something Next C# for(int i = 0; i <= 100; i++;) { //do something } Magic Values Avoid the use of “magic values.” Use constants instead: Wrong: VB.NET If Parishes.Count > 64 then
MessageBox.Show(“Invalid number of parishes.”)
End if

C#

If(Parishes.Count > 64)
{
MessageBox.Show(“Invalid number of parishes.”);

}

Correct:

VB.NET

Private Const MaxNumberOfParishes As Integer = 64
Private Const InvalidNumberOfParishesMessage As String = “Invalid number of
parishes.”
‘ In your function or subroutine:
If Parishes.Count > MaxNumberOfParishes Then
MessageBox.Show(InvalidNumberOfParishesMessage)
End if



C#

private const int MaxNumberOfParishes = 64;
private const string InvalidNumberOfParishesMessage = “Invalid number of
parishes.”
If(Parishes.Count > MaxNumberOfParishes)
{
MessageBox.Show(InvalidNumberOfParishesMessage);

}
Use Enum’s or constants file if required


Prefix interfaces with the letter I and use the interface keyword.

Use a noun (e.g. IComponent), noun phrase (e.g. ICustomerAttributeProvider), or an adjective (e.g. IPersistable)to name an interface.

Ex:

public interface IScanner {}


Building Strings

Building large strings in memory should use the System.Text.StringBuilder class as opposed to manually appending string parts into a string variable. This is necessary for the speed of the application. Building a string on your own instead of using the StringBuilder class is much slower.

Wrong:

VB.NET

Dim value as String = “”
For i as integer = 0 to 100
value += “A”
next

C#

int i;
for(i = 0; i <= 100; i++;) { Value += “A”; } Correct: VB.NET Dim sb as new System.Text.StringBuilder Dim value as String = “” For i as integer = 0 to 100 sb.Append(“A”) Next value = sb.ToString() C# StringBuilder sb = New StringBuilder(); for(int i = 0; i <= 100; i++;) { sb.Append(“A”); } string Value = sb.ToString(); Accessing the database through your .NET code

Do not create or execute SQL queries in the code behind of forms or within the same project as the user interface. All queries should be inside of the data access layer (DAL). If a dynamic query must be used, it should not be susceptible to SQL injection attacks.

Technorati Profile

No comments: