Question How do I avoid global variables or static class? - Best practice?

reyes

Member
Joined
Nov 11, 2016
Messages
20
Programming Experience
1-3
Hi all

I have a database table with payment methods (Cash, Credit Card etc.). These payment methods are visible on at least 2 forms (Winforms) in combo boxes.

At the moment, I have a DataTable that I populate a dictionary from with the id and name of each 'PaymentMethod' item (cash, debit card etc.). This only happens if the dictionary is null, so it knows to grab the information on application startup to detect any changes (no matter how rare). This is then bound to the combo boxes by using BindingSource - this all works fine and my combo boxes display what they should.

My question is: what is the best practice for using this offline dictionary to populate these different combo boxes whilst the user is using the application, and moving between forms? I don't want database connections every time the user moves between forms, but if I can help it, I'd also rather avoid global variables or static classes and properties, though I feel like my requirements demand such use?

Guidance appreciated!

Thanks
 
You pretty much have three choices:

1. Get the data once and put it somewhere that it can be accessed from anywhere in the project.
2. Get the data on demand for each form instance that will use it.
3. Get the data once for each form type and then have each instance of that type use that same source.

Option 3 is a hybrid approach that would work similarly to what you describe above except you'd be setting a static field from a static constructor in each form that needs the data. That way, you avoid a global variable but you also avoid retrieving the same data every time the user opens a form that needs it. If you have two forms that the user opens five times each, you'd retrieve the data twice rather than ten times.
 
You pretty much have three choices:
1. Get the data once and put it somewhere that it can be accessed from anywhere in the project.

Thanks very much for taking the time to help.

On point 1: does that mean I'd 'be going down the static class & field route?

Also, what would you personally recommend? I appreciate the choices so I can make my own decision, but I'm also curious to hear what may be the preferred method based on other factors (performance, sustainability, best practice, etc.).

Thanks again.
 
It would depend on how you've architected your application. If you have a distinct data access layer that uses something like Entity Framework then your question is moot. For a simple application that does its data access in the forms, it depends on whether you have a separate DataSet per form. If so then I'd be populating that table in the DataSet separately in each form. Otheriwse, I might be inclined to do it once for the application.
 

Latest posts

Back
Top Bottom