Busy working on an old VB6 project, recently converted to VB.NET. The application was originally written in the 1990s, and all variable declarations (Dim dbVersion As Single
and so on) are crammed together at the top of methods, generally out-of-sight from where the variable is used.
The style of "declare all variables at the top of the function" was commonplace in the 90s, enforced in the C90 and earlier K&R versions of the C language. Some languages, such as Delphi, still use this declarative style. But the C99 and later C-standards, C++, C# and modern VB.NET allow for variables to be declared wherever they are used (IMO, a huge improvement).
My question is whether there was ever a time when this style was enforced in Visual Basic or VBA (or indeed VB.NET)?
Suggested, taught in schools as a "best practice", but no, not enforced by the compiler - not to the extent that a declaration must appear before any executable statement in a procedure scope, no.
VB6/VBA code can declare locals anywhere within a procedure scope (the smallest possible scope in VB6/VBA); the catch is that Dim
(and Const
, also legal in local scope) statements aren't executable (you can't break on them), and I would guess the reason it was so warmly recommended to "just put them all at the top" is that local declarations must appear before the first use of a variable: having a block of declarations therefore ensures all local declarations are legal.
Caveat:
ReDim
statements are executable, and they act as aDim
declaration. It is perfectly legal to haveReDim someArray(1 To maxValue)
even ifsomeArray
wasn't previously declared, even withOption Explicit
specified.
But having a block of declarations at the top of a procedure isn't a modern best practice...
[...] are crammed together at the top of methods, generally out-of-sight from where the variable is used.
...and IMO this is exactly why.
VB.NET changed the rules of scoping a bit (you can now have an inner scope inside a procedure), but what it really did was to introduce a knowledge gap tight enough that VB6 devs wouldn't be too intimidated, but wide enough that the new language & framework could boast a new set of best practices - and the onboarding devs would just embrace them. New language, new ways: out with Hungarian Notation and walls of declarations at the top of procedure scopes - and just like that, the new recommendation was to declare variables where & as you need them, and to never prefix any identifier with a type abbreviation.
But much of the VBA crowd weren't devs, and didn't hop onto the .NET bandwagon, and essentially missed the memo with the updated best practices that could effectively apply in VBA/VB6 even though they were pushed for VB.NET. VBA/VB6 isn't necessarily stuck in 1997 though; the Rubberduck project (open-source, I manage it) aims to modernize the VBE, its tooling (static code analysis, refactorings, unit testing, etc.), and the coding practices around it.