Milad
Milad

Reputation: 127

What are the risks of declaring a variable in the middle of the code?

I usually see in almost all of VBA codes all variables are declared after e.g. Sub/Function name line

I know and I used variable declaration in the middle of some of my codes (Not inside a loop) and saw no problems.

I usually avoided that because I see most of VBA example codes have them declared right after the first line. I just want to know what are the risks from an expert/experienced VB programmer point of view.

Upvotes: 5

Views: 2043

Answers (4)

StayOnTarget
StayOnTarget

Reputation: 13048

I would try to declare variables in a location that conveys useful information to the next programmer, over and above being functionally correct. This normally means: follow the scoping rules of the language.

By declaring all variables at the top you are making them available (in scope) for the entire procedure. That increases the work for a reader in the future, trying to understand how they will be used. Better to have them as local as possible.

I would not declare them in a loop since that actually would not have significance in VB6/VBA - but someone else might find confusing or misleading, or worst case it may cause subtle bugs.

Of course remember that this is not the only coding practice that we should be mindful of - if the procedure is so long that the location of the variable declarations is a big problem, that's a really good sign that the procedure should be broken up into smaller discrete logical blocks. The variable declarations would just be a symptom, not the main cause.


IMO there were many bad programming practices back in the 90s and earlier when VBA/VB6 were invented, but the industry has significantly learned & improved since then. So code from that era (or inspired by it) is often not a good example.

Upvotes: 4

Ahmad
Ahmad

Reputation: 12737

Declaring your variables up front, at the top of your sub/function makes it easy for others (and perhaps for you if you come by the code after, say a month) to read and understand what your code needs to calculate, and what placeholders/variables are required for the code to function.

You can of course declare variables anywhere (as long as you remember not to use a variable unless you have actually declared it first). That can work, and it has no effect whatsoever on the performance of your code (unless your logic includes an early Exit Sub or Exit Function. In this case, there will be a difference in performance depending on if your code does actually allocate memory for the variables or not).

It just isn't good practice to declare some variables at the top then do some work, then declare another set of variables mid-code. There are exceptions of course. When the variable you declared mid-code is for a temporary use, or something like that.

Sub CalculateAge()
    Dim BirthYear As Integer
    Dim CurrentYear As Integer

    'Code to fetch current year 
    'Code to get BirthYear from user/or document
    'Code to report result
    
End Sub

Compare that with the following:

Sub CalculateAge2()
    Dim BirthYear As Integer
    'Code to ask the user or fetch the birth year from the document

    Dim CurrentYear As Integer
    'Code to populate currentYear 

    'Code to do the calculation and report result
End Sub

In the first example, there is a clear separation from variables and logic. In the second, everything is mixed.

The first example is a lot easier to read and understand, especially if you use a good naming convention.

If you look at how classes are written or defined, you will see properties usually are first declared, then methods/logic below. This is the common practice used to write code.

PS: In other languages, you can declare and assign variables in the same line. in C# or VB.Net you could say something like:

int Age = CurrentYear - BirthYear;   //C#
Dim Age As Integer = CurrentYear - BirthYear   'VB.Net

This is great if you use a lot of temporary variables, that you don't intend to declare ahead of time or maybe it would be more clear if declared mid-logic. But that's not possible in VBA. You need a separate line to declare a variable, and another to assign a value. You end up with a lot of Dim ___ As ___ statements. You might as well move the declaration part somewhere else to reduce distraction while reading the logic. Again, this works best if you use a good and consistent naming convention. If not, you end up in a worse situation like:

Dim w As Integer
Dim a As Integer
a = 42            'we don't know what this variable is for
                  'but we know its type from the previous line

Some_Lines_Of_code_And_Logic
' more code
' more code

w = 2             'we don't know what (w) is for, and we have to 
                  'look up its declaration to get a hint
                  'which might be tedious

Upvotes: 0

PChemGuy
PChemGuy

Reputation: 1719

Declare your variables, when you actually need them. When you have all declarations lumped at the top of the procedure, refactoring becomes much harder. And when you want to double check your declaration as you read your code (or, perhaps, someone else), searching it at the top may be again quite inconvenient, unless you procedure is short.

Upvotes: 4

GSerg
GSerg

Reputation: 78210

There are no risks of declaring it in the middle.

The effect of declaring a variable in the middle is that it can only be used after that point and not before (which is scope).
The lifetime of the variable is different: the variable is created (allocated and initialized to its respective flavour of zero) when you enter the procedure, but you may not actually use it until you reach its scope (the point in the procedure where it's declared).

Declaring inside or outside a loop does not make a difference in VB6/A as they do not have block scope, unlike VB.NET.

So there is no performance difference between the two approaches (because all variables are created when you enter the procedure), but there is a difference in usage (you may not use a created variable before its declaration line). If you think that distinction is helpful in making sure you are not using a variable wrongly, declare your variables only where needed. Otherwise you are free to pick any of the two approaches, just apply it consistently (it's probably not a good idea to declare most of the variables in the beginning and then some in the middle).

Upvotes: 7

Related Questions