Saturday, December 06, 2008

Improving ASP.NET code

I have an ASP.NET application that suffers from some problems.

We have a page that dynamically loads a lot of different components, and these components needs to access per-request properties of the application, such as user id, product name etc. Today this can be done something like:

string stateValueToGet = string.Empty;

// Coding horror..
// Component a is where stateValueToGet is parsed.
ComponentA compA = this.Parent.Parent as ComponetA;

if(compA != null)
{
stateValueToGet = compA.GetStateValue();
}

// do something with stateValueToGet ...

To begin with this is not good design to have components be dependent on each other like that. If the component should have a dependency it should probably only be to the page.

But alternative way to store these kind of per request values that need to be accessed in many different places during a page request is to use the HttpContext.Items property that allows you to store data as name-value pairs. However we should not access values directly from the Items collection but instead use proper C# helper classes or properties in the page class for that in order to hide validation, formatting etc.

One drawback with this solution is that dependencies among components will not be as clear but we should strive to minimize those anyway.

How to manage per-requst properties should be a core concern of the architecture.

In addition we need to handle session properties if those are used. Since session properties are used in a lot of different places these should be accessed using C# classes rather than properties in pages. An alternative way is to place these is a MasterPage or BasePage but i don't like that idea due to the fact that using this kind of inheritance can restrict reuse of components.

No comments: