Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guarding resources with Singleton?

I have read quite a few blog posts and answers on SO pointing to Singleton being a bad design. Previously I implemented a singleton CameraControl class. This class controls a camera which is connected to the system. Under the following knowledge:

  • Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).
  • Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).
  • My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).

Is my choice of making this class a singleton class a bad decision?

like image 950
Dat Chu Avatar asked Feb 02 '23 19:02

Dat Chu


1 Answers

Singletons are considered a smell because:

  • They are the moral equivalent of global variables, and thus their use hides dependencies in code rather than revealing them through interfaces.

  • They promote tight coupling because your code depends on a specific instance of a specific type. What if you wanted your UI to operate against a different camera manager some day?

  • They make unit testing difficult because they carry state with them for the entire lifetime of the program. When state is carried across from test to test, it can make tests state-dependent, which is a very big smell.

like image 123
Jollymorphic Avatar answered Feb 05 '23 16:02

Jollymorphic