Tuesday, February 21, 2006

State management technique

One thing that I hate is how most developers access session or cookies like this

1 Dim firstname As String = Session("firstName")

and then 100 times in the application you have the hard code of firstName. About a year ago Tim showed me this very simple and effective way to centralize this. I don't know if there is a name for this technique but I sure love it:

1 Public Class StateManager

2 Public Shared Property FirstName() As String

3 Get

4 Return StateEngine("fistName")

5 End Get

6 Set(ByVal Value As String)

7 StateEngine("FirstName") = Value

8 End Set

9 End Property


11 Private Shared Property StateEngine(ByVal key As String)

12 Get

13 Return System.Web.HttpContext.Current.Session(key)

14 End Get

15 Set(ByVal Value As Object)

16 System.Web.HttpContext.Current.Session(key) = Value

17 End Set

18 End Property

19 End Class

now whenever you need to get/set something from state all you have to do is:

1 Dim firstname As String = StateManager.FirstName

This also alows you to change your state management solution very quickly. If you wanted to move away from session to cookies you would only have to change the implementation in the StateEngine method.


Post a Comment

<< Home