Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP Session variables: Is "" same as IsEmpty?

In ASP an uninitialized Session variable Is Empty. I know that the correct way to check for a Session value, and remove a value, is the following:

IF NOT IsEmpty(Session("myVar")) THEN
  ' Go ahead and use Session("myVar")
  ...
  ' Now if we're all done with myVar then remove it:
  Session.Contents.Remove("myVar")
END IF

I've inherited a codebase where Application and Session variables are typically set = "" after use, and all tests for a value are of the form (Sessions("myVar") = ""). This test appears to work when the Session variable has not been declared ... or maybe it's just working by dumb luck.

Is it safe to use comparison with the empty string to test for a Session variable? I.e., is the following "practically as good" as the correct method shown above?

IF Session("myVar") <> "" THEN
  ' Go ahead and use Session("myVar")
  ...
  ' Now if we're all done with myVar then blank it:
  Session("myVar") = ""
END IF

Or should I refactor the codebase so that:

  1. All tests to determine whether a Session variable has been set are of the form IsEmpty(Session("myVar"))
  2. All session variables are Removed and not set = ""?
like image 209
feetwet Avatar asked Oct 19 '22 04:10

feetwet


1 Answers

Empty is a strange beast: it is simultaneously equal to both "" and 0. Seriously, try it:

dim x, y, z
x = Empty
y = ""
z = 0
Response.Write (x = y) AND (x = z)

It'll write out "True".

This means that testing for Not IsEmpty(myvar) is equivalent to testing myvar <> "", but IsEmpty(myvar) is not equivalent to myvar = "". Whether that mostly-theoretical difference bothers you or not is something only you can answer, but personally, I wouldn't waste time on refactoring.


If you do decide to refactor, I would suggest forgetting about IsEmpty and IsNull and whatnot, and just using the & "" "hack":

If Session("myvar") & "" <> "" Then

This'll transparently handle Nulls and Empties without you needing to write a whole bunch of code.

like image 158
Martha Avatar answered Oct 21 '22 22:10

Martha