Web design, SQL, and .NET for the young, up-and-coming developer Dot Net Yuppie

The Session object is extensively used for many projects, but it is often misused to the point of becoming unwieldy if it isn’t appropriately managed.

The ‘Traditional’ Management
The traditional method of referencing a session key is to use a string literal:

Session("SessionID") = 12345
Session("SessID") = 12345
Session("SID") = 12345

What’s wrong with the traditional method?

  1. It forces the developer to hand-write the session key each time — there is no code completion and no check for typographical errors or small differences in the name of the session key.
  2. Developers take extra time to look up the proper session key name. In the example above, there are three session keys (SessionID, SessID, and SID) that could easily be confused between different developers.
  3. Development speed is decreased because code completion is not utilized, meaning developers have to type more unnecessary characters.
  4. Poor management of session keys doesn’t keep all the key names in one place — developers can’t easily modify a key name without having to modify all the code in the project.

A better method
Instead of referencing a session key as a string literal, you should create a class that contains all of a project’s session keys. As you can see in the following example, session keys can be stored as individual string variables, or you can even create a structure that contains a group of related session keys.

Public Class SessionObjects

	Public Shared SessionID as String = "SessionID"
	Public Shared ShoppingCart As String = "ShoppingCart"
	Public Shared MoreSessionVars as String = "SessionVars"

	Public Structure SomePlugin
	    Shared PluginPreference1 As String = "SomePlugin_PluginPreference1"
	    Shared PluginPreference2 As String = "SomePlugin_PluginPreference2"
	    Dim null
	End Structure

End Class

'Usage:
Session(SessionObjects.SessionID) = 12345
Session(SessionObjects.SomePlugin.PluginPreference1) = "False"
IDE Code Complete

A session object addresses the main problems with string-literal session keys — it allows for code completion, which increases development speed and reduces typographical errors, and manages all the session keys in one place.

Although it may seem like extra work to create a class to contain all of your session keys, it’s going to save you a headache in the long-run, especially for anyone that might maintain your code in the future.

For those subscribed to The DotNetYuppie RSS feed, stay tuned because this article is one of several articles to come related to developing an efficient, standardized facade for enhanced project management.

Leave a Reply