Clean Up Your Session Access With Session-Backed Classes

One of my favorite techniques to refactor ugly web code into cleaner, OO code is creating session-backed classes. Often, developers go directly after session values, setting and getting them throughout their web pages. I hate this for a number of reasons--the biggest two are (1) it is very difficult to deal with decentralized session access, i.e. if you need to change a variable name, or manage everywhere a variable is called, it can be spread out all over your site; and (2) if you misspell the variable name somewhere (clearly session variable names bypass compile-time checking), your code will not behave the way you expected.

Session-backed classes free you from this problem, give you a nice quasi-OO wrapper over the session, centralize access to the variables, and even provide intellisense when you are developing against them. Additionally, since creating a session-backed class is a trivial process, you can spend about an hour and create a session-backed class generator to take out the grunt work.

Let's look at the fundamentals you need for a session-backed class:

1) You need a new class that will represent a logic unit (a user, an employee, a sale)
2) You need a constructor to take a reference to your session management; this is optional if you want to assume you can use the current HTTP context
3) You need a list of properties that will be made available by this class
4) A best practice is to use a prefix for the variables to allow the values to be easily grouped, and to clearly show what class created the variables


Now, let's take a look at some session-backed class code. Here is a simple class with one property, making use of the current HTTP context for session management:


Public Class Employee

    Public Property Name() As String
        Get
            Return HttpContext.Current.Session(Prefix & "Name")
        End Get
        Set(ByVal value As String)
            HttpContext.Current.Session(Prefix & "Name") = value
        End Set
    End Property

    Private Function Prefix() As String
        Return "Classes.Employee."
    End Function

End Class


That's really all there is to it. Referencing this variable from anywhere else in your application will give you a great OO-style interface into the session:


    SessionValue = Employee.Name


Meanwhile, you are not responsible for any additional code behind the scenes to serialize and deserialize the object, which is perfect for classes that are working with values used by legacy apps that call directly into session (i.e. apps that you can't easily change).

0 comments:

Post a Comment