Thursday, September 5, 2013

Coding Standards



Developers should keep few things in mind while they are developing projects. We will focus on developers to agree on a standard and follow it throughout software development.

Some Standards:
  •   Always use XML comments for each major block of code. We don’t focus to write comment on every line of program. But only on the major block of code like if you are developing a class, then first add comment with class. Secondly add comments on the public methods or members of class. An example of this is as
    /// Connect to database through SQL
    /// and perform data manipulation operations
    ///
    public class DBConnection
    {
        SqlConnection connection = null;
        SqlCommand cmd = null;
        SqlDataAdapter da = null;
        DataSet ds = null;
       
        ///


        /// default constructor
        ///
        public DBConnection()
        {
            connection = new SqlConnection();
        }

        ///


        /// open connection
        ///
        ///
        private bool OpenConnection()
        {
            try
            {
                connection.ConnectionString = AppSettings.ConnectionString;
                connection.Open();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

      }



Note: This is only a part of class to show how to use XML comments in your code.

  •   Avoid using constants or magic numbers in the program. For this there is a project “common” already added to the solution. For such constants define Enums there and use them. See below example.

public enum OrderStatus
        {
            OrderReceived = 1,
            OrderReady = 2,
            OrderDelivered = 3,
            OrderPaid = 4
        }

Here rather than using the constants we are using enum throughout the program.

  •  Never use/access configuration files settings directly. I mean using configuration manager on the forms or pages you develop is not good practice. For this we have added a class “AppSettings”. In this class define your own constants and populate them from the configuration file. See below snap code for this.


public static class AppSettings
    {
        public static string ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ToString();
      
    }

  •   Make constants with upper case letter like in above example.
  •   Keep track of the warnings as well while developing. This will suggest you many things regarding your code. For example if you define a variable and don’t use in code, you will get a warning regarding this. By doing this you will remove un necessary code/variables from the file.
  •  For collections try your best to use “foreach” like loops and not the traditional for or while loops.
  •   Empty string comparison or assignment is not appreciated through (“”), but instead use the string.Empty. You will mostly need this on clearing the form controls.
  •  Your code should use exception handling and give proper messages to user.
  •   Don’t write code directly in the form control events, instead make your own functions/methods and call them from your events as required.
  •   Make your form controls user friendly and useable through keyboard. For this use hot keys and accelerator keys.
  •   Use Pascal casing for class names and method names like in following  code example


public class HelloWorld
{
  void SayHello(string name)
  {
    ...
  }
}

  •   For variables use camel notation, avoid Hungarian notation like in the visual studio 2000.

In camel notaion a variable is declare with first lower case letter and afterwards, every first   character of a word is uppercase. For example “totalCount” is in camel notation form.
  •   Do not use abbreviations. Use name, address, salary etc. instead of nam, addr, sal.
  •   Do not use single character variable names like i, n, x, etc. Use names like index and temp.
  •   File names should match the class name. Though C# does not force for this rule as in java.
  •   The curly braces should be on a separate line and not in the same line as if, for, etc.

if ( ... ) 
  {
   // Do something
 
  }
 
  •   Use a single space before and after each operator and brackets.
if ( showResult == true )
  {
   for ( int i = 0; i < 10; i++ )
   {
    //
 
   }
  }
  •   The method's name should tell what it does.
  •   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.
  •   Use language specific data types and not the alias defined in system name space like int,long and not System.Int32 or System.Int64
  •  Use Meaningful, descriptive words to name variables. Do not use abbreviations.


Good:
string address
int salary

Not Good:
string nam
string addr


  •  Do not use single character variable names like i, n, s etc. Use names like index, temp
  •  Prefix boolean variables, properties and methods with “is” or similar prefixes.
  •   Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables
Control
Prefix
Control
Prefix
Label
lbl
Repeater
rep
TextBox
txt
Checkbox
chk
DataGrid
dtg
CheckBoxList
cbl
Button
btn
RadioButton
rdo
ImageButton
imb
RadioButtonList
rbl
Hyperlink
hlk
Image
img
DropDownList
ddl
Panel
pnl
ListBox
lst
PlaceHolder
phd
DataList
dtl
Table
tbl
Validators
val














  •   Use TAB for indentation. Do not use SPACES.  Define the Tab size as 4
  •   Comments should be in the same level as the code (use the same level of indentation)
  •   Curly braces ( {} ) should be in the same level as the code outside the braces.
  •  Use one blank line to separate logical groups of code.


       bool SayHello ( string name )
       {
              string message = "Hello " + name;
              DateTime currentTime = DateTime.Now;

              string formatedmessage = message + ", the time is : " +             currentTime.ToShortTimeString();

              MessageBox.Show ( formatedmessage );

              if ( ... )
              {
                     // Do something
                     // ...

                     return false;
              }

              return true;
       }

  •   Use #region to group related pieces of code together. If you use proper grouping using #region, the page should like this when all definitions are collapsed
  •  Do not make the member variables public or protected. Keep them private and expose public/protected Properties
  •   Do not programmatically click a button to execute the same action you have written in the button click event. Rather, call the same method which is called by the button click event handler.
  •   Never hardcode a path or drive name in code. Get the application path programmatically and use relative path
  •   Error messages should help the user to solve the problem. Never give error messages like "Error in Application", "There is an error" etc. Instead give specific messages like "Failed to update database. Please make sure the login id and password are correct."
  •   Avoid public methods and properties, unless they really need to be accessed from outside the class. Use “internal” if they are accessed only within the same assembly.
  •   Avoid passing too many parameters to a method. If you have more than 4~5 parameters, it is a good candidate to define a class or structure
  •   If you are opening database connections, sockets, file stream etc, always close them in the finally block. This will ensure that even if an exception occurs after opening the connection, it will be safely closed in the finally block
  •   Use StringBuilder class instead of String when you have to manipulate string objects in a loop. The String object works in weird way in .NET. Each time you append a string, it is actually discarding the old string object and recreating a new object, which is a relatively expensive operations.

Consider the following example:

public string ComposeMessage (string[] lines)
{
   string message = String.Empty;

   for (int i = 0; i < lines.Length; i++)
   {
      message += lines [i];
   }

   return message;
}

In the above example, it may look like we are just appending to the string object ‘message’. But what is happening in reality is, the string object is discarded in each iteration and recreated and appending the line to it.

If your loop has several iterations, then it is a good idea to use StringBuilder class instead of String object.

See the example where the String object is replaced with StringBuilder.

public string ComposeMessage (string[] lines)
{
    StringBuilder message = new StringBuilder();

    for (int i = 0; i < lines.Length; i++)
    {
       message.Append( lines[i] );
    }

    return message.ToString();
}