Franc Stratton's .NET (TM) Web Application, OOP, and SOA Architecture & Programming Site

A site devoted to ASP.NET (TM), SilverLight (TM) and Browser-Based WPF (TM) Applications, IIS Services, and OOP Architectures

Home     Architecture Overview     WF/WCF/WPF     Data Store     Standards     .NET Security     Resources     jQuery     Silverlight     Developer Tips     Blog     Site Map      
Code Formatting
Code Notation
Passing Parameters
LINQ
AJAX
Database
SDLC (ALM)
ASP.Net Callbacks
Dirty Flag
Code Formatting Policy
 

Visual Studio has a comprehensive list of code formatting options that are configurable within the IDE, as are code snippets. These features effectively eliminate the need to manually prepare a set of formatting standards. The formatting options are listed in the following sections, and all that remains for a development team is to agree the options, configure the respective IDEs, and note them as in-house standards. These standards are referenced below in this policy statement.

Namespaces

Put namespaces at the top of the code page with an open brace on a new line. Mark the closing namespace brace with a comment to identify the beginning brace match.

namespace DHSSample
{

}//namespace DHSSample

Regions

Demarcate all code page regions with opening (#region) and closing region tags (#endregion). E.g.:

#region Example Region
……………………………………………..
#endregion

Using or Imports References

Mark all code page “using” or “imports” statement list with region tags just below the code page namespace. E.g.:

#region Class Using References
using System;
using System.Data;
using System.Configuration;
using System.Collections;
#endregion

Code Page Headers

Include a page header on all code pages with the purpose delineated within the ///



//---------------------------------------------------------------------------
/// Author: Franc Stratton
/// Date 8/8/2007
/// Derived From: MyNameSpace.AppBase.BP
/// Updated:
/// Updated:
///

/// Description: UI page for Domain (E.g., Intake, Concilliation, etc)
///
//---------------------------------------------------------------------------

Derived Page Guidelines

ASPX web form pages should be derived from the DHS.AppBase BP (Base Page) abstract class if the programmer needs the functionality offered by this base class. Business domain classes should be derived from the DHS.AppBase BLL (Business Logic Layer) abstract class if shared business base class functionality is necessary. Data access domain classes should be derived from the from the DHS.AppBase DAL (Data Access Layer) abstract class since Enterprise Library Data Access functionality is in the DAL base class. Classes that do not need base class functionality should be derived from Visual Studio defaults. For example, if a web page requires Base Page functions, then derive the ASPX page from BP:

public partial class _Client : BP
{

}//public partial class _Default : BP

Private and Public Fields and Properties

Private and public fields and properties should have a region just below the code page class name. E.g.:

#region Private and Public Fields and Properties

private string db_Message = string.Empty; //field for Database Error Message

public string DBMessage //property for Database Error Message
{
    get { return db_Message; }
    set
    {
        if (value != null && value.Length != 0)
        {
            db_Message = value.Trim();
        }//if
        else
        {
            //throw a parameter exception
            throw new ArgumentException("Parameter value may not be set to null or empty.");
        }//else
    }//set
}//public string DBMessage

Class Constructors and Destructors

Domain classes that utilize one or more constructors and a destructor should have regions for them below the private and public fields and properties in a code page. E.g.:

#region Class Constructors
//base class contstuctors should be protected per VSTS code analysis
protected BLL()
{
    //
    // TODO: Add constructor logic here
    //
}//protected BLL()
#endregion

#region Class Destructor
~BLL()
{
    // Simply call Dispose if implemented in your class.
    Dispose (false);
}
#endregion

Class Method XML Comments

All class methods should have an xml comment that summarizes what operation the method will perform. E.g.:

protected void btnSearch_Click(object sender, EventArgs e)
{
    //---------------------------------------------------------------------
    ///

    /// Description: Used to search for Client list based on Last Name
    ///
    /// Sender of Click Event
    /// Client Event Arguments
    /// na
    ///--------------------------------------------------------------------

Programmer Comments

Do use programmer comments liberally to explain the lines used in a method to accomplish a task. E.g.:

//Check Dataset to see that it doesn't equal 0 rows
if (ds.Tables[0].Rows.Count != 0)
{
    //Only use the session for DataTable or DataSet. If you
    //need a few records to page in the datagrid or datalist
    //Did not use session here since no paging necessary
    //Session["clientDS"] = this.clientDS;
    this.grdSearch.DataSource = ds;


    //Bind DataSet to datagrid
    this.grdSearch.DataBind();


    //DataGrid invisible until bound to DataSet
    this.grdSearch.Visible = true;


    //inform the user of the number of records in the grid list
    this.lblMessage.Text = "Record(s) found: " + ds.tables0].Rows.Count.ToString();


}//if (ds.Tables[0].Rows.Count != 0)

Spaces

Spaces improve readability by decreasing code density. Here are some more guidelines for the use of space characters within code:

• Do use a single space after a comma between function arguments.
    Right: Console.In.Read(myChar, 0, 1);
    Wrong: Console.In.Read(myChar,0,1);
• Do not use a space after the parenthesis and function arguments
    Right: CreateFoo(myChar, 0, 1)
    Wrong: CreateFoo( myChar, 0, 1 )
• Do not use spaces between a function name and parenthesis.
    Right: CreateFoo()
    Wrong: CreateFoo ()
• Do not use spaces inside brackets.
    Right: x = dataArray[index];
    Wrong: x = dataArray[ index ];
• Do use a single space before flow control statements
    Right: while (x == y)
    Wrong: while(x==y)
• Do use a single space before and after comparison operators
    Right: if (x == y)
    Wrong: if (x==y)

Indentation

Tab characters (\0x09) should not be used in code, and all indentation should be done with 4 space characters. Set the Visual Studio IDE default to 4 spaces for tabs if the defaults have been changed.
    • Indent block contents below an open brace
    • Indent select (VB.NET) or switch (C#) contents
    • Indent case labels

switch (cIDDS.Tables[0].Rows[0][3].ToString().Trim())
{
    case "Dr.":
        this.ddlPrefix.SelectedIndex = 1;
        break;
    case "Mr.":
        this.ddlPrefix.SelectedIndex = 2;
        break;
    case "Mrs.":
        this.ddlPrefix.SelectedIndex = 3;
        break;
    case "Ms.":
        this.ddlPrefix.SelectedIndex = 4;
        break;
    default:
        this.ddlPrefix.SelectedIndex = 0;
        break;
}//switch (cIDDS.usp_GetClientsByID[i].Prefix.ToString())

New lines and braces

• Place “else” on a new line
• Place “catch” on a new line
• Place “finally” on a new line
• Place open brace on new line for C# types
• Place open brace on new line for C# methods
• Place open brace on new lines for C# anonymous methods
• Place open brace on new lines for C# control blocks (e.g.; for, if)

public void GetClientByLastName(out DataSet cDS, string lastName)
{
//---------------------------------------------------------------------
///
/// Description: Get Client by last name to populate search grid
///
/// last name for search
/// DataSet
//---------------------------------------------------------------------
//Set up dataset
DataSet ds = new DataSet();
try
{
//Make call to DAL to fill dataset with last name as parameter
domainDAL.GetClientByLastName(out ds, lastName);
}//try
catch (Exception ex)
{
//User message standard subject to change since may come from
//a resource file with standard canned messages
this.UserMessage = "An error occurred accessing the ARTS database by client last name.";
//domainDAL.DBMessage added to error
if (domainDAL.DBMessage != "")
{
string errorMessage = ex.Message.ToString();
//Logic for logging error to exception handling web service or Performance Monitor
}
}//catch (Exception ex)
cDS = ds;
}//public void GetClientByLastName(out DataSet cDS, string lastName)