Wednesday, May 9, 2012

Best Practices in coding

  •  Pascal Cashing is First character of all words are Upper Case and other characters are lower case. Ex: CostCenter
  •   Camel Casing - First character of all words, except the first word are Upper Case and other characters are lower case. Ex: costCenter
  •  Use the prefix “I” with Camel Casing for interfaces ( Example: IVehicle )
  •  Do not use m_ prefix when declaring member variable name. All variable should use Camel case
  •  Use meaningful and descriptive variable name  like string Address;
  • Do not use single characters like I,s instead of this use like Index, temp
  • Do not use variable name which resemble keyword.
  • Prefix Boolean variable and properties with is . Ex. Boolean IsNameExits
  • Namespace names should follow the standard pattern 
    • companyname.productname.toplevelmodule.bottomlevelmodule
  • Use appropriate prefix ui for different controls. Below is the list of items
  • Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.
  • 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
  •  File name should match with Class name. Use Pascal case while creating file Name.
  • Curley braces and comments should be on same level. Like  below
    • // Format a message and display
    • string fullMessage = "Hello " + name;
    • DateTime currentTime = DateTime.Now;
    • string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
    • MessageBox.Show ( message );
  •  Use one blank line to separate logical code block.
  • The curly braces should be on a separate line and not in the same line as if, for etc. that will increase the readability of the code.
  • Put the logical code block in region and #region so that when developer collapse the definition it will separate the code accordingly.
  • Avoid writing big methods. Try to make the method of 1-40 lines and if the function is getting bigger than separate it in sub functions.
  • Do not put hardcode values in the code instead of use constraints and define it on starting on the file.
  • Use String.compare instead of converting them upper or lower case.
  • Use String.isNullorEmpty instead of “”
  • Use enum wherever required. Do not use numbers or strings to indicate discrete values.
Good:
       enum MailType
       {
              Html,
              PlainText,
              Attachment
       }

       void SendMail (string message, MailType mailType)
       {
              switch ( mailType )
              {
                     case MailType.Html:
                           // Do something
                           break;
                     case MailType.PlainText:
                           // Do something
                           break;
                     case MailType.Attachment:
                           // Do something
                           break;
                     default:
                           // Do something
                           break;
              }
       }
 
 
Not Good:
 
       void SendMail (string message, string mailType)
       {
              switch ( mailType )
              {
                     case "Html":
                           // Do something
                           break;
                     case "PlainText":
                           // Do something
                           break;
                     case "Attachment":
                           // Do something
                           break;
                     default:
                           // Do something
                           break;
              }
       }
  • Never hardcode a path or drive name in code. Get the application path programmatically and use relative path. Never assume that your code will run from drive "C:". You may never know, some users may run it from network or from a "Z:".
  • If a wrong value found in the configuration file, application should throw an error or give a message and also should tell the user what are the correct values.
  • When displaying error messages, in addition to telling what is wrong, the message should also tell what should the user do to solve the problem. Instead of message like "Failed to update database.", suggest what should the user do: "Failed to update database. Please make sure the login id and password are correct."
  • 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.
  • Never access database from the UI pages. Always have a data layer class which performs all the database related tasks. This will help you support or migrate to another database back end easily.
  • Show short and friendly message to the user. But log the actual error with all possible information. This will help a lot in diagnosing problems.
  •  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, better to create a class and then send as parameter.
  • Do not store large objects in session. Storing large objects in session will consume lot of server memory as number of user increases.
  • Always use style sheet to control the look and feel of the pages. Never specify font name and font size in any of the pages. Use appropriate style class. This will help you to change the UI of your application easily in future. Also, if you like to support customizing the UI for each customer, it is just a matter of developing another style sheet for them
  • If you initialize a numeric variable to a special number other than 0, -1 etc, document the reason for choosing that value.
  • Never do a 'catch exception and do nothing'. If you hide an exception, you will never know if the exception happened or not. Lot of developers uses this handy method to ignore non-significant errors. You should always try to avoid exceptions by checking all the error conditions programmatically. In any case, catching an exception and doing nothing is not allowed. In the worst case, you should log the exception and proceed.
  •  When you re throw an exception, use the throw statement without specifying the original exception. This way, the original call stack is preserved.
  •  You should always explicitly check for errors rather than waiting for exceptions to occur. On the other hand, you should always use exception handlers while you communicate with external systems like network, hardware devices etc. Such systems are subject to failure anytime and error checking is not usually reliable. In those cases, you should use exception handlers and try to recover from error.

No comments: