Writing ASP.NET code… the right way. (Posted by Aaron)

There are always 10 good ways to solve a typical coding problem.  Each solution might use a slightly different approach – but usually in the end you wind up with the same result.  While this is common in all types of development, it seems to multiple by 100 when you enter the world of web development.  When writing code to solve an ASP.NET/C# problem I could probably come up with 20 different ways to reach the same conclusion.  However, 20 different ways doesn’t always mean 20 good ways – and finding a good way is the key to everything.

One of the practices that our team is really pushing hard on when writing new ASPX applications is ensuring that each and every page (from a code behind perspective and aspx perspective) follows a consistent pattern/flow.  There’s nothing worse than working in an ASPX project and having to stumble around on each and every page to figure out what is really going on.  It’s maddening… it’s inefficient… and it leads to mistakes… which ultimately lead to bugs.  I’ve found that by following a consistent pattern/flow in the code behind you save yourself a ton of time in the long run.  Here’s a simple example from a recent project:

private void Page_Load()
{
      Response.Expires = 0;
      LoadSettingsFromQueryString();

       if (!IsPostBack)
       {
           InitializeControls();
           LoadControlsFromSettings();
           LoadData();
       }
       else
       {
           LoadSettingsFromControls();
       }
}

Each page in this project has a Page_Load that looks just like this (or very, very close to this).  When adding new features to a page it’s easy to jump in and quickly understand what the page is doing because each page is going to behave the same from a pattern/flow perspective.  Some will argue that having a structure in place like this “reduce creativity” or be a “nuisance to implement”.  I choose to disagree though.  Having consistent code doesn’t inhibit creativity… and it’s not hard to implement.  Rather, having consistent code provides a framework for creativity and will make your project MUCH easier to understand and maintain.   This may seem like simple stuff, but I’m amazed at how often I run into code that doesn’t follow the simplest of guidelines such as these.

Aaron