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:
- 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.
- DRY - You can use the connection from any method in the class.
- Shorter code (Again, not always good).
- Again, logically, the connection does not describe the object, the object's methods just use it.
local (method) variable:
- Methods open the connection only when they need it*.
*Although, even using a field, you could use the
usingstatement to close the connection when needed.
- 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?