Friday, September 28, 2012

Code optimization and Best practices for ASP.Net C# Developers


Last week I had a good time with code review, all the guys who did coding are 3-4 years of experience in Microsoft technologies. But still there is scope for Optimization and best practice. Here in this blog post I’ll show you some of them.

1] A field can be made read-only

Consider the following example, Admin_Settings class has a private object ObjDB (an object of class Database)
Code:
public partial class Admin_Settings : System.Web.UI.Page
{
    private Database ObjDB = new Database();
}
Here, this object can be Readonly, by marking this readonly, we get to ensure that this class will not inadvertently modify this object anywhere within its methods.
Code:
private readonly Database ObjDB = new Database();
The same can be applied for Variables if they they are only being assigned in the constructor and offers to create an additional safeguard



2] Use 'var' keyword when initializer explicitly declares type

The var keyword is fairly contentious in terms of usage, but if there’s one instance where its use is sensible, it’s in initializations alike to the following:
Code:
DataSet DsPaidAmount = new DataSet();
Since the type is declared on both left and right-hand sides of the initialization statement, I suggest to remove the type on the left-hand side and replace it with var, i.e.:
Code:
var DsPaidAmount = new DataSet();
Or even further, you can remove redundant initializer and write it as
Code:
 DataSet DsPaidAmount;


3] Use declaration closer to usage


Consider the following example, where many variables are declared which are not really closer to usage. The Database object DsPaidAmount is declared at the top, and used at the very bottom (so, declaration and usage are not closer).
Code:
public void Receipt()
{
        double PreviousPaidAmount = 0;
        double TaxAmount = 0;
        //variable declared here
        DataSet DsPaidAmount;
        double TotalAmount = 0;
        double PreviousDiscount = 0;
        
        . . . . . . 
        . . . . . . 

        if (some condition)
        {
            . . . . . .
            . . . . . .
        }
        else if (another condition)
        {
            . . . . . .
            . . . . . .
        }
        else if (!another condition)
        {
            . . . . . .
            . . . . . .
        }

        if (statement > 0)
        {  
            //Variable used here! tooooo far from declaration            
            DsPaidAmount = ObjReceipt.GetPaidAmount(somevalue);
        }
        else
        {
            //statement
        }
}
Here, we can move declaration closer to it’s usage, as follows:
Code:
if (statement > 0)
{  
    //Declared and used at same place!
    DataSet DsPaidAmount = ObjReceipt.GetPaidAmount(somevalue);
}
else
{
    //statement
}

Further, for better memory management we can use the “using” constructor, and also remove the type on the left-hand side and replace it with var as follows:
Code:
if (statement > 0)
{  
   using (var DsPaidAmount = ObjReceipt.GetPaidAmount(somevalue))
   {
       // some statements
   }
}
else
{
   //statement
}


4] Remove unneeded 'else' keyword

Some if-else conditions can have their else clause removed. Consider the following method:
Code:
public double roundNum(double num)
{
   double floorValue = Math.Floor(num);
   if ((num - floorValue) > .5)
   {
      return (floorValue + 1);
   }
   else
   {
      return (floorValue);
   }
}
In the above, the else statement can be safely removed because its if clause returns from the method. Thus, even without the else, there’s no way you’ll be able to proceed past the if clause body. We can write it as follows:
Code:
public double roundNum(double num)
{
   var floorValue = Math.Floor(num);
   if ((num - floorValue) > .5)
   {
      return (floorValue + 1);
   }
   return (floorValue);
}
Even better; we can write it by converting it to “?:” operator
Code:
public double roundNum(double num)
{
   var floorValue = Math.Floor(num);
   return (num - floorValue) > .5 ? floorValue + 1 : floorValue;
}


5] Join declaration and assignment

Consider the following example, where Type can use Implicitly typed local variable declaration and Join declaration and assignment
Code:
if (Page.IsValid)
{
     List<string> ServiceList = new List<string>();
     ServiceList = GetChecked(ChkService);
}
Finally by removing redundant initalizer, using Implicitly typed local variable declaration, joining declaration and assignment and with a good naming convention for local variables, we can write this as follows:
Code:
if (Page.IsValid)
{
   var serviceList = GetChecked(ChkService);
}


6] Convert “IF” statements with “?:” operator

Consider the following example
Code:
if (GvVisit.Rows.Count > 0)
{
   BtnCompleteFollowUp.Visible = true;
}
else
{
   BtnCompleteFollowUp.Visible = false;
}
Can be written with pretty optimized version using “?:” operators as follows:
Code:
BtnCompleteFollowUp.Visible = GvVisit.Rows.Count > 0 ? true : false;
Or even better by removing unneeded conditional ternary expression usage. Since condition returns a boolean value
Code:
 BtnCompleteFollowUp.Visible = GvVisit.Rows.Count > 0;

No comments:

Post a Comment