Mr. Cluey : How To ...? : Variable Conflict


How do I prevent variable conflict?

A variable conflict occurs when a variable name is defined twice in the same scope. Within a single file, this problem is generally simple to fix; but things can get a bit tricky when multiple files are involved.

For example, I wrote a class for interacting with the Registry. One of the parameters that I needed was HKEY_LOCAL_MACHINE, so I defined it in the class library.

Everything was just fine until I used this library in conjunction with mswconst.inc, which also defined the variable. The compiler was quick to complain.

One variable, one file

If the variable in question is part of the public interface of a library, that is to say, if you are expecting to use that variable outside of the file in which it is defined, you must make ensure that the variable is defined in only one place.

For example, in the scenario above, I could have included mswconst.inc in my registry library. However, there is an awful lot of stuff in mswconst - I really only want the one value

Another possibility would be to factor out the variables I needed into a small file (regconst.inc), and include that file in both mswconst and in the registry library. The downside to this approach is that it forces me to "fix" mswconst every time I reinstall it.

Hide implementation details with private

In my case, I wasn't trying to export the value - I was just using it inside my library - it was a private implementation detail. That being the case I can prevent the compiler problems I faced by declaring the local instance of the variable to be private.

// also defined in mswconst.inc
private const HKEY_LOCAL_MACHINE = 0x80000002;

Problem solved - of course, the danger in this approach is that I now have to worry about maintaining the variable in two different places. In this particular instance, it isn't a major concern, but it could be if HKEY_LOCAL_MACHINE wasn't under pretty strict control.


Mr. Cluey : How To ...? : Variable Conflict

Return to ATS Automated Testing Resources Page