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

4

5

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.

Terylene answered 19/12, 2021 at 8:48 Comment(3)
most of VBA example codes follow the coding style from the previous century, when many programming languages required declarations to end before the first executable statement. You don't have to follow this style, unless you want to use it.Ivetteivetts
Worth reading the last paragraph of Mathieu Guindon 's (old) post dimensioning a variable inside a loop: "Dim statements are not executable: VBA allocates the memory space for a procedure's declarations before a single line runs in that procedure. Stepping through code (F8 while debugging) skips Dim statements for that reason (you cannot break on a Dim statement). ...variables declared inside an If or With or Do .., is in the same scope as any variable declared at the top of a procedure."Packaging
@Packaging This EXACTLY what I wanted know, I wanted to know if declaring a variable based on a condition makes my code to run faster or not . Thanks.Terylene
B
7

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).

Baboon answered 19/12, 2021 at 9:12 Comment(0)
C
4

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.

Carmarthenshire answered 19/12, 2021 at 15:6 Comment(0)
L
4

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.

Lashawn answered 20/12, 2021 at 12:38 Comment(2)
I would add that when you work on legacy code I think it is important to follow the coding convention and style of that code, even if we might consider those conventions or styles bad practice by today's standards. Consistency makes working on code easier and keeps the code cleaner.Officiate
@BrianMStafford I agree, there's no good rationale for changing working code if it doesn't need to be changed. And normally one should make the most reasonable minimal change that will work. For entirely new modules within an older project however, I think some discretion can be applied as to the style (being aware of team standards, etc.)Lashawn
V
0

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
Vicarial answered 19/12, 2021 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.