Are static local variables bad practice?

Related question in C ++: Static local variables in bad practice methods?

In VB.NET, when I need a simple counter or something that increments every time the method is called, I often find that I am 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 it recommended in VB.NET and OOP in general?

+6
source share
2 answers

Are static local variables bad practice?

No. Static local variables relate exactly to nonlocal private variables: they have a smaller scope. Since you always want the area to be as small as possible (= better encapsulation), local statics can be advantageous compared to private variables.

On the flip side, local static variables can be difficult to initialize correctly. If complex initialization is required (for example, if you need to reinitialize a variable later), local static variables may not be suitable.

+8
source

I would recommend NOT .

Static in Visual Basic means that one or more declared local variables must continue to exist and retain their last values ​​after the procedure in which they are declared is completed. Link: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/modifiers/static

So why are you doing this? The next time you enter this Sub, you will still be reinitializing this variable. I don’t think you can even access it if you don’t have a second instance of this class, and if both instances are running at the same time, the value of β€œa” can affect the value of β€œa” in the second example. If it was not intended, it would be a disaster. As stated in the previous answer, the smaller the volume, the better.

So, if I'm not mistaken, this will be a very bad practice.

0
source

Source: https://habr.com/ru/post/886707/


All Articles