Related C++ question: Static local variables in methods a bad practice?
In VB.NET, when I want a simple counter or something that increments each time a method is called, I often find myself writing code like:
Private Sub tmrRefresh_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrRefresh.Tick
Static a As Integer = 0
a += 1
'...rest of method depends on a
End Sub
Is this recommended in VB.NET and OOP in general?
Static Methods/Variables are bad practice. In short: Yes. There are many disadvantages and static methods should almost never be used. Static methods allow procedural/functional code to be shoe-horned into an Object Oriented world.
Static local variables are useful when we want to have only one instance of our object in the local scope, which means all calls to the function will share the same object. The same can also be achieved by using global variables or static member variables.
Yes, that problem will remain the same. If your code is restricted by the fact that there is only one global variable, then you lose functionality, or your code may not be thread safe, and so on. That's a problem and needs to be handled for a static variable just as for a global variable.
So, by using a local variable you decrease the dependencies between your components, i.e. you decrease the complexity of your code. You should only use global variable when you really need to share data, but each variable should always be visible in the smallest scope possible.
Are static local variables bad practice?
No. Static local variables differ in exactly one regard to non-local private variables: they have a smaller scope. Since you always want to keep scope as small as possible (= better encapsulation), local statics can be advantageous over private variables.
On the flip-side, local static variables may be hard to initialise correctly. If a complex initialisation is required (for example, if you need to re-initialise a variable later on), local static variables may be unsuitable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With