What's the best practice for storing global variables in a VB.NET WinForms app. For example when a user logs into an app you may want to store a CurrentUser object which can be accessed throughout the app. You could store this as an object in a module or create a class which contains members for all the required globals, you would still need to store the instance of this somewhere though.
Does the framework provide an easy solution to this?
I think 'don't' is a little harsh, here's a quote from Steve McConnell:
Used with discipline, global variables are useful in several situations
I think just like a good carpenter has the right tool for the job and will use the right tool if the need arises, programmers should also use all of the tools at their disposal.
Straight from the 'Tour de Force' Code Complete are several reasons to use global data:
McConnell also says:
Use Global Data Only as a Last Resort. Before you resort to using global data, consider a few alternatives.
here are the alternatives he lists:
The things i've mentioned here get great coverage in the fantastic book Code Complete
There is approximately one best practice regarding the use of global variables.
"Don't."
(If this sounds harsh, consider that things like CurrentUser normally belong in something that the environment already maintains a unique instance of for you, such as the Session. Look up the API to obtain the current session, store your CurrentUser there and retrieve it from there. Don't create your own globals, which will render your app harder to maintain and vulnerable to race conditions.)
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