HttpContext Can Break Object Oriented Principles

May 29th, 2007 by Sameer | Filed under .NET articles.

A situation came up when I was coding..  I was debugging a certain class, and somehow some value was mysteriously changing, and when I did a search in the code, I could not figure out how it was changing.  Somehow the Session value for "SalesCode" was changing yet there was no reference to it.

The culprit??  One of the functions in a business object in App_Code was using HttpContext.Current without having that explained and documented and also without having it as one of the parameters..

Thus, using HttpContext.Current can break OOP (Object Oriented Principles).

If you want to make a change to the HttpContext (Session, or what not), pass it!

Here is the code that was messing with my session:

public static void SetSalesCode(int newValue)
{
   HttpContext.Current.Session["SalesCode"] = newValue;
}

I modified the code, so that it still achieves the same effect, but it is much more obvious what it
does and easier to track down

public static void SetSalesCode(int newValue, HttpContext htc)
{
   htc.Session["SalesCode"] = newValue;
}

Other Interesting Posts

Share Your Thoughts

Valid XHTML 1.0 Transitional Valid CSS!