Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable (or alternative) best practice in .NET

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?

like image 318
Simon Avatar asked Feb 03 '09 16:02

Simon


2 Answers

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:

  • Preservation of global values
  • Streamlining use of extremely common data
  • Eliminating tramp 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:

  • Begin by making each variable local and make variables global only as you need to
  • Distinguish between global and class variables
  • Use access routines

The things i've mentioned here get great coverage in the fantastic book Code Complete

like image 116
Phaedrus Avatar answered Sep 17 '22 12:09

Phaedrus


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.)

like image 26
Morendil Avatar answered Sep 21 '22 12:09

Morendil