Session Variables Are Evil! Enter OO

For those of us who learnt to program, one of the first things you learn is:

"Global variables should be avoided, and only used when absolutely necessary"

Session variables are global. In most web page designs, session variables are necessary. But they present the problem that they are global. If a system is large enough, there is a huge risk of Session variables being overwritten, introducing subtle bugs that are hard to find. Another problem with session variables is that they don't store type information, even though you can shove any type into them.

There is a solution to this problem. This creates a little programming overhead with lots of positive effect.

Step 1:
Create an abstract class with a public Session property. Add a constructor that takes an HttpSessionState object, then initialises the session property to point to it.

Step 2:
Create a derived class that inherits from class mentioned above. Give it a name that you can use as a session variable class name.

Step 3:
Add properties to the class with correct return types for session variables. Handles null checks and initialisation in the get method, assign to the session variable in the set method. Name the property the same name as the session variable.

Step 4:
Declare an instance of the class in your Page class.

Step 5:
Initialise the instance in your Page_Load method, using the parametrised constructor.

Step 6:
Reference the class instance to access your session variables, now type safe, null checked and optionally documented, with the added benefit of quick access via call tips in Visual Studio.

You could argue that this is a misuse of Objects, but it's better than global variables being abused. Also try to remember the effect of referencing the wrong key in your Session state. This will also make it easier for the next programmer to find his way around your session variables, and make you more conscientous when creating session variables.

Comments