I have multiple business entities in VB.NET Windows Forms application. Right now they are instanced on application startup and used when needed. They hold descriptions of business entities and methods for storing and retrieving data. To cut the long story short, they are somewhat heavy objects to construct (they have some internal dictionaries and references to other objects) created and held in one big global variable called “BLogic”.
Should I refactor this so that each object is created when needed and released when out of scope? Then every event on UI will probably create a few of this objects.
Should I strive to minimize creation of new objects or to minimize number of static and global objects? Generally I am trying to minimize the scope of every variable but should I treat this business logic objects specially?
Let’s look at the two options you’ve presented:
Single Global Instances
Pros:
Cons:
Unique per function instances
Pros:
Cons:
This is not meant to be an exhaustive list, but it does point out the main tradeoffs as I can see them. Obviously, you know more about the situation and which tradeoffs are acceptable. A few judiciously chosen globals can be useful, but like most people I would lean away from having a lot of globals unless they represent something that there can only be one of, like a SerialPort, or something that the entire application should only have one of, like an ApplicationSettings class.
Don’t undervalue your time (both now and later when you come back for maintenance) as a cost. Sometimes a “better” solution may actually be worse because it takes too long to implement. Often “good enough” turns out to be, well, good enough.