Where to declare variables

H

Harlan

I understand the difference in Dim, Private, Public (Global) as to the SCOPE
of the variable and where it can be used.

My question is: What are the pros and cons of keeping a variable private as
apposed to declaring all variables as Public in one module. I am working on
an application which will end up with a large number of variables and it
seems it would be "easier" to keep track of them if I declared them all in
one place instead of at the form or procedure level.

Thanks
 
R

Roger Carlson

Well, Scope IS the answer to your question. Where and how will the variable
be used? There is very little reason to declare a variable globally when it
is only used in one subroutine. Also, you can reuse variables that are
declared at the subroutine level.

For instance, I use "i" a lot as a counter variable. Suppose I have a
routine with a "FOR i = 1 to <somevalue>" NEXT Loop. Further, suppose that
in that loop, I have a call to another subroutine that also has a counter.
If "i" is declared globally, I can't use that in my other routine. So I
would have to create a different variable, even though that counter is only
used in one routine.

A similar problem develops with object variables: database objects or
recordset objects. If I use "rs" as a recordset variable, I could not use
that again anywhere in the database. Using it again, even to reference the
same dynaset, could have serious consequences. So I would have to have rs1,
rs2, ... etc. even to view essentially the same data.

In addition, good structured programming practice says that your variables
should have the smallest scope possible. This leads to the least amount of
confusion. I disagree that it would be easier to keep track of in a global
module. It is much easier to keep track of when it is as close as possible
to the code that uses it.

Lastly, in Access, Global Variables have a nasty habit of vanishing,
especially when errors occur. To get around this, I most often store global
variables (when I use them, which is not often) in a control on a hidden
form or in a temp table. They have more permanence there.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top