Pages

Thursday, April 18, 2013

Tips: Simplify code for better approach

Developers always concentrated on the problem and try different algorithms. Often the first solution won’t be the best. They think again, be creative, try a different approach. Come up with more ideas and choose from better. The better the algorithm is, the better the solution.

However in this blog post, I'm not going to discuss about algorithms. I will be concentrating on tips which (C#) developer neglect in a hurry to solve problems. Just by following the items one can simplify the code for better understanding and readability.

1.  Never use unused “using” statements within a class/page. Use “Remove and Sort” under “Organize Usings” from the context menu
2.    Pascal Casing (first word capitalized). Use PascalCasing for classes, types, methods and constants
3.    Camel Casing (all but first word capitalized). Use camelCasing for local variables and method arguments
4.    Try to skip underscores (“_”) to separate words
5.    Variables names may follow Hungarian Notation or camel case
Ex:
string firstName;
6.    Method names must follow Pascal Notation
Ex:
public string GetUserFirstName()
       {
              // Some statements...
       }
7.  Class variables or member names should start with an “_”
Ex:
int _familyId;
8.    Always check the negative conditions first to exit the method
Ex:
Old:
            if (!IsPostBack)
       {
           // Some Statements
       }
New:
            if (IsPostBack) return;
       // Some Statements
9.    Never use “this” keyword to identify page controls or properties
10.  Try to reduce the no. of lines of code as well as unused variable declarations
Ex: The method allows us to create a random string using Global unique Identity class (GUID)
Old:
private string generateString()
       {
            string pName;
            Guid fileName = Guid.NewGuid();
            pName = fileName.ToString().Substring(0, 8);
            return pName;
       }
New:
private string generateString()
       {
            return Guid.NewGuid().ToString().Substring(0, 8);
       }
11.  Use implicitly typed local variable declaration (var) only when necessary
Note1: When the class name of an object declaration and initialization is same, we can replace the declaration with var keyword.
Ex:
Old:
BlogBase bb = new BlogBase();
New:
var bb = new BlogBase();

Note2: We need to declare the object with class name only if the initialization of an object is done by the resultant output of a method or function.
Ex:
FamilyMember fm = FamilyMember.SelectByMultipleFields("FamilyID", familyId, "MemberId", memberId); // The method will return an object of type FamilyMember class
12.  Try to reduce if... else... statements either using logical assignment or ternary operator ( ? : )
Ex1: Using logical assignment
Old:
            if (Emailids.Tables.Count == 0)
       {
              lbtnDelete.Visible = false;
       }
       else
       {
              lbtnDelete.Visible = true;
       }
New:
            lbtnDelete.Visible = Emailids.Tables.Count != 0;
Ex2: Using ternary operator
Old:
if (stringMode.Equals("new"))
ViewState.Add("Mode", "new");
else
ViewState.Add("Mode", "ex");
New:
ViewState.Add("Mode", stringMode.Equals("new") ? "new" : "ex");
13.  Use LINQ & lambda expressions whenever necessary
Ex:
Old:
string bColor = "";
for (int i = 0; i < aColor.Length; i++)
bColor = bColor + aColor[i];
New:
string bColor = aColor.Aggregate(bColor, (current, t) => current + t);
14.  We can reduce the delegate creation by skipping the associated event handler Class
Old:
Master.FamilyRefreshed += new EventHandler(MasterFamilyRefreshed);
New:
Master.FamilyRefreshed += MasterFamilyRefreshed;
15.  Use null-coalescing operator (??) whenever necessary
Ex:
int? x = null;
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
16.  Declare local variables as close as possible to the first time they're used
17.  Try to avoid global variables
18.  Never make redundant “toStrings()” calls
Ex:
string code = Request.QueryString["Code"].ToString();
19.  Don’t comment the trivial statements, but strategically write paragraphs if needed in specific sections
20.  Make sure your code is source safer with tools viz. VSS, SVN, TFS, Git etc.,
21.  Never be in a state of “Probably be ok” w.r.t use-case; Test and Verify each use-case
22.  Communicate with team when in doubt
23.  Never reinvent/rewrite the code from scratch. Always check your existing code base from same or different projects, teams and if nothing stands go for Google
24.  An engineer truly becomes a wiser "professional" only after the software been released only then 80% of blood, sweat and tears in maintenance

Feel free to add tips within the comments section below based on your experience.