VBScript / ASP Classic - Avoiding name conflict with function parameters

147 Views Asked by At

I'm working on an old application that often declares variables that seem to be global, using identifiers likely to be used elsewhere.

When writing a function, some parameters happen to have the same name as those global variables, and it is hardly avoidable, because one doesn't know if that identifier is already in use by one of these global variables, or it might be, but within a script that ends up not being called.

SomeRandomPage.asp :

foo = "bar" ' Not sure if it's declared with Dim or not

MyFunction.asp :

Function MyFunction(foo) ' Same name as global variable "foo"
    foo = foo & "123"
    MyFunction = foo
End Function

If the function affects a value to that parameter, the global variable also appears to be modified, like VB Script didn't care about variable scopes at all.

Dim bang : bang = "hello"

Response.Write foo ' "foo"

bang = MyFunction(bang)

Response.Write foo ' "hello123"

The solution I was suggested is to declare local variables in my function using Dim, copying my parameters into those local variables, and using those local variables instead of the parameter.

Function MyFunction(foo)
    Dim localFoo : localFoo = foo
    localFoo = localFoo & "123"
    MyFunction = localFoo
End Function

As poor as VB Script can be, I can't imagine that this dirty method would be the only solution to avoid this global variable overwriting behaviour.

So my question is : how can I prevent global variables from being overwritten by assigning values to function parameters that happen to have the same name ?

2

There are 2 best solutions below

2
Étienne Laneville On

You could create a clsGlobals class for your global variables:

Class clsGlobals
    Public foo
End Class

You'd create a single instance of this class:

Dim Globals
Set Globals = New clsGlobals

And replace your global foo variable with Globals.foo

This would resolve the naming conflicts and also make it obvious the variable you are using is a global variable. This does not prevent global variables from being overwritten but I think it's a good solution.

0
LesFerch On

Here's the OP's code with the only change being MsgBox instead of Response.Write:

foo = "bar"

Function MyFunction(foo)
  foo = foo & "123"
  MyFunction = foo
End Function

Dim bang : bang = "hello"
MsgBox foo
bang = MyFunction(bang)
MsgBox foo

The OP claims that foo will be set to "hello123", but running this code as a VBS file, foo remains set to "bar".

Here are two possible explanations:

  1. In the actual production code, foo is being passed into the function (instead of bang).

  2. In the actual production code, the function argument is something different than foo, but foo is being changed within the function.