vendredi 16 octobre 2015

Is this singleton design pattern bad?

The problem:

For simplicity i'll use a simple example. In a sample application, a Class-A reads some data.

Class-A then spawns Class-B, which then spawns Class-C. So in all there is a 3-level-hierarchy of classes A --> B --> C

Class B creates & manages custom objects based on the data found in class A. I have simply passed the data from class-A to class-B in the form of function/method parameters.

Class C, however, is different. It has 2 functions/methods that give it its data.

  1. firstMethod(arg) - which gives it data to work with. (called on class-B)
  2. otherMethod(otherArg) - with gives it other data to work with.

It was spawned by Class-B and the data that it needs from Class-B will be passed to it passed to by class-B through firstMethod(arg1). However, there is another data set that class-C needs to run properly. This other parameter has nothing to do with class-B; It would seem wrong to pass this information through this classes as a parameter to get to class-C.

How can I get this information from class-A to class-C without using class-B? What I did was create a Singleton class-S.

Class-S has defined within it the methods/functions (not variables) of class-A. After setting it up, Class-C can now call its otherMethod(otherArg) on Class-S which calls the needed function and returns the needed data directly from class A.

A-->B-->C
^       |
|___S___|

The Questions:

I've listen some of the problems of singletons ive seen around the net.

  1. From this link, They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell. [my edit] - While class-S is being used as a global instance, Class-c has its dependencies clearly defined. The methods/functions that's needed for it to work is defined in its interface.
  2. from this link, They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases. [my edit] is this setup still tightly coupling class-C with the singleton? If Class-C is to be unit tested, the singleton is not needed (at least i don't think so). Since the functions are clearly defined a mock class can fake its data.
  3. They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other. [my edit] Given the setup I'm not sure this will be a problem?

Any pointers on this will help much. Please no hate.. I googled but didn't find many definitive answers. Thanks. Any thoughts?

Aucun commentaire:

Enregistrer un commentaire