Is instantiating a single database connection like this and returning that instance to all callers a good software engineering practice?
That depends.
- The code as it stands doesn't check if the connection is still alive, and reconnect if it isn't. Assuming this is a simplified version and that the real code performs such a check, then:
- As long as the single instance of
Database
is injected into mallall callers, rather than being accessed via a service locator, then it's good practice.
The reason why it's good practice to inject a singleton class like this is that it can be referenced via an interface inside those callers, and thus a mock database connection can be provided to them when running unit tests.