I have here a Vb.Net employee management application. It has employees, managers, teams, trainings and so on.

The way the application is set up now, data is read from the database in the startup form (frmMain) load event and kept in that forms public properties. After that all other forms (and there is many of them) reference those lists (list (of employee), list of (team)) usging those properties. For example

dim emp = frmMain.Employees.Find(Function(x) x.ID = 128) , or
dim team1 as new Team

I feel that this is a very bad way to solve this problem, but I'm stuck on deciding how this should be done.

Some singleton class that would keep all those lists (there is lots of them) instantiated on application startup, or is there a better way to do this?

  • 2
    While most of us were taught to hate globals, this design you describe is not as bad as it sounds. The frmMain is being used as the singleton (which is certainly is in the context of the one application). You could separate out a global singleton with properties that everyone can read, but why would that be much better if you are wedded to a single main form and are not varying the user interface. – Mike Jul 24 '14 at 14:02

I have solved this in the past by creating a public module called Globals.vb that contains one or more VB Structure types that logically group variables together. You can then create a single public instance of each structure. For example, an ApplicationState structure variable could have collection-oriented properties for your employees and teams. This lets you write code like this:

if ApplicationState.Teams.Contains(thisTeam) then ...

Or, from your example:

Dim emp = ApplicationState.Employees.Where(function(z) z.ID = 128).FirstOrDefault

This puts all global variables into a single, (relatively) easy to understand place and format. It also lets you use the Structure's constructor to initialize your values.

| improve this answer | |
  • Singleton pattern; I've done exactly the same thing to great effect and see little reason not to in this sort of project scope. – msanford Jul 24 '14 at 20:36
  • Roger: When you use the word "structure" do you actually mean the vb.net container type structure or just a singleton class? – GlutVonSmark Jul 25 '14 at 11:32
  • I mean the VB Structure. There are many other ways to do the same thing, of course, but I find that the functionality of the Structure type maps pretty well to these requirements. I'll edit my answer to clarify. – Roger Jul 25 '14 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.