Skip to main content
added 227 characters in body
Source Link
David Arno
  • 39.5k
  • 9
  • 93
  • 127

Is instantiating a single database connection like this and returning that instance to all callers a good software engineering practice?

That depends.

  1. 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:
  2. 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.

Is instantiating a single database connection like this and returning that instance to all callers a good software engineering practice?

That depends.

  1. 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:
  2. As long as the single instance of Database is injected into mall callers, rather than being accessed via a service locator, then it's good practice.

Is instantiating a single database connection like this and returning that instance to all callers a good software engineering practice?

That depends.

  1. 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:
  2. As long as the single instance of Database is injected into all 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.

Source Link
David Arno
  • 39.5k
  • 9
  • 93
  • 127

Is instantiating a single database connection like this and returning that instance to all callers a good software engineering practice?

That depends.

  1. 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:
  2. As long as the single instance of Database is injected into mall callers, rather than being accessed via a service locator, then it's good practice.