Thursday, November 6, 2008

The art of making the simple complex

I was going through our use of session variables in Asp.net today at work and found code very similar to the following on multiple places:

If Session("foo") Is Nothing Then
    Session.Add("foo", value)
Else
    Session.Remove("foo")
    Session.Add("foo", value)
End If

First off, if you thought you really had to use the "Add" method to set the value why not do the following:

If Not Session("foo") Is Nothing Then
    Session.Remove("foo")
End If 

Session.Add("foo", value)

Now, ofcourse, there's really no need to check if the value exists in the session before removing it since the "Remove" method throws no exception, so we'll just write:

Session.Remove("foo")
Session.Add("foo", value)

But ofcourse, any sensible developer would instead write:

Session("foo") = value