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

3 comments:

  1. I see people do that kind of stuff all of the time. It is quite crazy. One line turned into many simply because someone didn't realize that if you're just going to overwrite the value you should just use the indexer.

    I've also seen plenty of overly complex code. I am pretty sure everyone has done at least one of those before.

    ReplyDelete
  2. Quite nifty. Brainy, yet simplistic. But what happens if Session Is Nothing?

    ReplyDelete
  3. Well, if Session is nothing, you've got a bug.

    ReplyDelete