Monday, 13 July 2015

CODING STANDARDS



Coding Standards

1)   Naming Conventions:
·        Pascal
·        Camel

1)   Use Pascal casing for Class names
//class name pascal casing
publicclassNamingConventions
    {
    }


2)   Use Pascal casing for properties
//property pascal
privatestringEmployeeID { get; set; }



3)   Use Pascal casing for Method names and camel casing for the arguments
//Method name pascal argument camel
privatevoidEmployeeName(stringemployeeName)
        {
        }

4)   Use Pascal casing for Interface. Use prefix “I”.

interfaceIEmployee
    {
    }

5)    Use Camel casing for variables
inttotalCount = 0;
stringemployeeName = string.Empty;

6)   Use Meaningful, descriptive words to name variables. Do not use abbreviations.
Not Good:
stringaddr;
intsal;

Good:
            string address;
            int salary;

7)   Do not use single character variables for loops. Use names like index, temp
for ( int index = 0; index < count; index++ )
{
           
}

8)   Do not use variable names that resemble keywords.

9)     Prefix boolean variables, properties and methods with “is” or similar prefixes.
Ex: private bool  _isFinished;
10)          Naming for controls
Control
Prefix
Label
lbl
TextBox
txt
DataGrid
dtg
Button
btn
ImageButton
imb
Hyperlink
hlk
DropDownList
ddl
ListBox
lst
DataList
dtl
Repeater
rep
Checkbox
chk
CheckBoxList
cbl
RadioButton
rdo
RadioButtonList
rbl
Image
img
Panel
pnl
PlaceHolder
phd
Table
tbl
Validators
val

11)          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.



12)          Keep private member variables, properties and methods in the top of the file and public members in the bottom. 
13)          Avoid writing very long methods. A method should typically have 1~25 lines of code. If a method has more than 25 lines of code, you must consider re factoring into separate methods.

14)          Method name should tell what it does. Do not use mis-leading names. If the method name is obvious, there is no need of documentation explaining what the method does.

Good:
            voidSavePhoneNumber ( string phoneNumber )
            {
                        // Save the phone number.
            }

Not Good:

            // This method will save the phone number.
            voidSaveDetails ( string phoneNumber )
            {
                        // Save the phone number.
            }

15)          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.

Good:
            // Save the address.
            SaveAddress(  address );
           
            // Send an email to the supervisor to inform that the address is updated.
            SendEmail( address, email );              
           
            voidSaveAddress ( string address )
            {
                        // Save the address.
                        // ...
            }
           
            voidSendEmail ( string address, string email )
            {
                        // Send an email to inform the supervisor that the address is changed.
                        // ...
            }

Not Good:

            // Save address and send an email to the supervisor to inform that
// the address is updated.
            SaveAddress( address, email );

            voidSaveAddress ( string address, string email )
            {
                        // Job 1.
                        // Save the address.
                        // ...

                        // Job 2.
                        // Send an email to inform the supervisor that the address is changed.
                        // ...
            }
16)          Do not hardcode numbers. Use constants instead. Declare constant in the top of the file and use it in your code.

However, using constants are also not recommended. You should use the constants in the config file or database so that you can change it later. Declare them as constants only if you are sure this value will never need to be changed.

17)          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.

18)          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.

//avoid
publicvoid Checkout(stringshippingName, stringshippingCity,
stringshippingSate, stringshippingZip, stringbillingName,
stringbillingCity, stringbillingSate, stringbillingZip)
{

} 

//DO
publicvoid Checkout(ShippingAddressshippingAddress,BillingAddressbillingAddress)
{
}


19)          If you have a method returning a collection, return an empty collection instead of null, if you have no data to return. For example, if you have a method returning an ArrayList, always return a valid ArrayList. If you have no items to return, then return a valid ArrayList with 0 items. This will make it easy for the calling application to just check for the “count” rather than doing an additional check for “null”.

20)          If you are opening database connections,  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.


21)          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 (inti = 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 (inti = 0; i<lines.Length; i++)
    {
       message.Append( lines[i] );
    }

    returnmessage.ToString();
}
22)          Do not write comments for every line of code and every variable declared.

23)          Write comments wherever required. But good readable code will require very less comments. If all variables and method names are meaningful, that would make the code very readable and will not need many comments.
24)          Use Nullabledatatypes whenever required
int index = 0; // simple declaration of int
int? index = null; // nullable data type declaration

25)          Use Runtime constants over the compile time constants
Runtime constants are those which are evaluated at the runtime and declared with the keyword “readonly”. On the other side, compile time constants are static, evaluated at the time of compilation and declared with the keyword “const”.
publicreadonlystring CONFIG_FILE_NAME = "web.config"; // runtime constant
publicconststring CONFIG_FILE_NAME = "web.config"; // compile time constant

So, what is the need to prefer readonly over const variables? Compile time constants (const) must be initialized at the time of declaration and can’t be changed later. Also, they are limited to only numbers and strings. The IL replaces the const variable with the value of it over the whole code and thus it is a bit faster. Whereas, the Runtime constants (readonly) are initialized in the constructor and can be changed at different initialization time. The IL references the readonly variable and not the original value. So, when you have some critical situation, use const to make the code run faster. When you need a reliable code, always prefer readonly variables.

26)          Use “is”  and “as” operators while casting
It is better to use “is” and “as” operator while casting. Instead of Explicit casting, use the Implicit casting. Let me describe to you with the example of a code.
// this line may throw Exception if it is unable to downcast from Person to Employee
var employee = (Employee)person;

In the above code, suppose your person is a Customer type and when you are converting it to Employee type, it will throw Exception and in that case, you have to handle it using try{} catch{} block. Let’s convert the same using “is” and “as” operators. See the below code:

// check if the person is Employee type
if(person is Employee)
{
            // convert person to Employee type
            employee = person as Employee;
}

// check if the person is Customer type
elseif(person is Customer)
{
            // convert person to Customer type
            customer = person as Customer;
}
 In the above code, you can see that, in the second line I am checking whether the person is aEmployee type. If it is of type Employee, it will go into the block. Else if it is a Customer type, will go to the block at line 12. Now, convert it with the “as” operator, as shown in line 5. Here, if it is unable to convert, it will return as null but will not throw any exception. So, in the next line, you can check whether the converted value is null.

For reference:
http://www.codeproject.com/Articles/539179/Some-practices-to-write-better-Csharp-NET-code
http://www.codeproject.com/Articles/118853/Some-Best-Practices-for-C-Application-Development







Session 2
27)          Never use a name that begins with a numeric character.

28)          Avoid using Unused  variables:

Description: http://www.codeproject.com/KB/cs/539179/Step1.jpg

29)          Disposing unmanaged code and managed code

30)          Avoid number of returns:

//avoid
if(product.Price>15)
{
returnfalse;
}
elseif(product.IsDeleted)
{
returnfalse;
}
elseif(!product.IsFeatured)
{
returnfalse;
}
elseif()
{
//.....
}
returntrue;

//DO
var isValid = true;
if(product.Price>15)
{
   isValid= false;
}
elseif(product.IsDeleted)
{
   isValid= false;
}
elseif(!product.IsFeatured)
{
   isValid= false;
}
return isValid;

Always Use Properties instead of Public Variables

Reason behind this is, it makes your code properly encapsulated in OOPs environment. By using getters & setters, you can restrict the user directly accessing the member variables. You can restrict setting the values explicitly thus making your data protected from accidental changes. Also, properties give you easier validation for your data. Let's see a small code:
publicclass Person
{
               publicstring name;
 
               publicstring GetNameInLowerCase()
               {
                               returnstring.IsNullOrWhiteSpace(name) ? 
                                                             string.Empty : name.ToLower();
               }
 
               publicstring GetNameInUpperCase()
               {
                               returnstring.IsNullOrWhiteSpace(name) ? 
                                                             string.Empty : name.ToUpper();
               }
}
In the above example, you will see you have to check every time for the Null value as somebody from outside can easily change the value accidentally and create a Bug in your code. If you don't want that Bug in your code, what you will do is, use the property implementation of the variable (making it private) and then access the property. This gives more reliability over your code. Let’s see an example:
publicclass Person
{
               publicstring name;
 
               publicstring Name
               {
                               get
                              {
                                              returnstring.IsNullOrWhiteSpace(name) ? string.Empty : name;
                               }
                               set { name = value; }
               }
 
               publicstring GetNameInLowerCase()
               {
                               return Name.ToLower();
               }
 
               publicstring GetNameInUpperCase()
               {
                               return Name.ToUpper();
               }
}


Now in this case, you don't have to think about checking the value against Null every time. The getter implementation of the property will take care of it. So, once implementation but use in multiple places. So, if someone explicitly sets the “Name” property to null, your code will have no impact on it. This is just a sample code to discuss with you about the need of property instead of public member variable. Actual implementation may vary based on your requirement.



Description: http://www.codeproject.com/images/minus.gif Collapse | Copy Code
publicclass Person
{
               publicstring Name { get; privateset; }
               publicstring Age { get; }
}
If you don't want anybody to set the Property explicitly from outside, you can just only implement the getter inside the property implementation or mark the setter as private. Also, you can implement the properties from any interface, thus gives you more OOPs environment.

31)           Decide between Value Types and Reference Types


Whenever you need to create a type, first ask yourself a question “What you want and Why you want it?”. If you could answer your question, you can decide between the type you want to use. If you want to store your data, use value types and when you want to create an instance of your type by defining the behavior, use reference types. Value types are not Polymorphic whereas, the Reference types can be. Value types are most efficient in terms of memory utilization over reference types and produce less help  garbage. If you want to pass values to a method implementation, decide what you want to do and based upon your requirement, decide between value types and reference types. Use of reference type variables actually change the original value but use of value type will create a copy of the original variable and pass across the method. Thus, it protects your original value from accidental changes. Let's see them in real example. In the below code, we are passing the variable “i” as value type and in the method implementation incrementing it by 10. As it was passed by value, you will see the original value “5” as output of the program code.


staticvoid Main(string[] args)
{
               int i = 5;
               SetValues(i);
 
               System.Console.WriteLine("Currently i = " + i); // will print "Currently i = 5"
}
 
staticvoid SetValues(int x)
{
               x += 10;
}
In the below code, as we are sending “i” as a reference, it will change the original value of “i” inside the method and hence you will see 15 as the output in the screen.
staticvoid Main(string[] args)
{
               int i = 5;
               SetValues(ref i);
 
               System.Console.WriteLine("Currently i = " + i); // will print "Currently i = 15"
}
 
staticvoid SetValues(refint x)
{
               x += 10;
}
Hence, decide before you start the implementation, else once implemented it will be very difficult to change them over your huge application.

No comments:

Post a Comment