Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static local variables bad practice?

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?

like image 939
Flash Avatar asked Apr 26 '11 13:04

Flash


People also ask

Are static variables good practice?

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.

When should a static local variable be used?

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.

Are static global variables bad?

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.

Why is it good practice to use local variables?

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.


1 Answers

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.

like image 174
Konrad Rudolph Avatar answered Oct 05 '22 18:10

Konrad Rudolph