This post has been migrated from www.experimentsincode.com, we apologise if some of the images or content is missing

This post has been migrated, original date 16 Dec 2008 When looking at code I often see session/cache access like this:
        public void AddToBasket(Product newProduct)
        {
            Basket myBasket = (Basket) Session["basket"];
            myBasket.AddProduct(newProduct);
            Session["basket"] = myBasket;
        }
    The problem with this is that the session is accessed using a natural language. The problem with using a natural language is that the word "basket" could be used by another developer to store something else in the session in a different bit of code and therefore overwriting by mistake any value stored in the state object. The other problem is that every time the developer needs to access the object the developer has to write code to cast the object to the correct type. A better solution is to hide this all in a property and use a guid as the key for the object in session/cache. The advantage of using the guid is that you can guarantee that no other developer will pick the same key. This ensures that your state object is never over overwritten by mistake:
          public Basket CurrentBasket
          {
              get
              {
                  return (Basket)Session["{DED12A99-E792-43ce-8899-253A0ECC0C6B}"];
              }
              set
              {
                  Session["{DED12A99-E792-43ce-8899-253A0ECC0C6B}"] = value;
              }
          }
          public void AddToBasket(Product newProduct)
          {
              CurrentBasket.AddProduct(newProduct);
          }
      A developer can now get direct access to the object stored in state without worrying about how the object is stored. This means it could be stored in some other state mechanism by only changing the accessors in the property. Of course you still need to deal with the issue of a null reference when using the state object, but this can be easily handled by modifying the accessor's bodies to handle the null exception to either create a new object or throw an error. The other change I would make is to store the key in a variable to make the code a little more readable and manageable:
          private const string _currentBasketKey = "{4BD1E9CC-AAAF-44f3-B487-9425B76BE89F}";
          public Basket CurrentBasket
          {
              get
              {
                  if(Session[_currentBasketKey] == null) Session[_currentBasketKey] = new Basket();
                  return (Basket)Session[_currentBasketKey];
              }
              set
              {
                  Session[_currentBasketKey] = value;
              }
          }