-1

I am using c# but the question was more towards software engineering principals so I am asking the question here.

There are so many questions here but mostly they say :"How to use global variables in c#?" and "Are global variables are bad?". But my question is about "How" to avoid global variables in my scenario.

I've written a class that works as data access layer. I've 2 objects of this class. One pointing to main database and second pointing to reports database. The connection string are not constants rather a form is displayed at application startup and user enters the server name, login name and password. Now all other classes need to use these objects to work with database.

I have a strong feeling that these 2 objects should be global but I want to avoid if somehow this is possible?

MJ Khan
  • 99

2 Answers2

2

It is a question of dependencies. The connection string and credentials could be passed to the constructor of the data access layer class. Objects depending on the DAL could be passed a reference to the DAL instance in their constructor.

If you have two seperate DAL's, objects which depend on both would be passed both DAL instances in the constructor.

By passing the dependencies in constructors rather than accessing globals, the dependency chain becomes more explicit and you avoid "hidden" dependencies.

JacquesB
  • 61,955
  • 21
  • 135
  • 189
0

I'm somewhat unsure who says that global objects are always bad. There is at least one well-accepted object-oriented pattern that explicitly involves global objects - the singleton pattern. For C#: http://csharpindepth.com/Articles/General/Singleton.aspx

"Global variables are bad" probably just means that you should not store the two instances of your DAL class in some globally accessible variables. And indeed this is not necessary. As you have two instances, the singleton pattern won't work. But you could have a simple factory/pool class. It would have a getDAL(id) method that would take an identifying string ("main" or "reports") and return the DAL object (and create it if it does not exist yet). Then in each object that uses a DAL, you can retrieve the necessary DAL object into a local variable.

Here is the advantage over just having global variables. Imagine a third database is added later. You can switch to using it anywhere by just switching the ID where the DAL object is retrieved, without going through all references to a global variable.