When methods use a database connection, should the connection be a static field, an instance field, or a local variable?
Here are my doubts. I dithered which are correct and which are baseless. I tried to give sources to my assumptions, but most of it stems from things I have read here and there, and probably did not understand properly:
static
fields:
Pros:
- DRY - You can use the connection from any class.
- Shorter code (not always a good thing).
Cons:
- This is practically creating a global variable*, which is considered bad in OOP.
*Perhaps you could refer to the connection as global constant which is not concidered bad programming?- Sometimes fields are referred as states since they describe the state of the class. But logically, the connection do not describe the class, the class's methods just use it.
instance fields:
Pros:
- DRY - You can use the connection from any method in the class.
- Shorter code (Again, not always good).
Cons:
- Again, logically, the connection does not describe the object, the object's methods just use it.
local (method) variable:
Pros:
- Methods open the connection only when they need it*.
*Although, even using a field, you could use theusing
statement to close the connection when needed.Cons:
- DRY - Very repetitive code.
So, as I said, I can see advantages and disadvantages of the three approaches. But what is the most common approach, and more importantly - the most accurate approach from the perspective of OOP? And which approach leads to better performance?
Thanks.