čtvrtek 19. března 2009

Repeat after me: "Singleton is my enemy"

Some people call singletons controversial some call them evil. I'd say the second group consists of those who pray to OOP.

What are the reasons why they are evil especially in large scale software design?
  1. they cripple locality - singleton is equal to a global variable - it's functionality can suddenly appear anywhere in the program. This decreases dramatically understandability of the system and often forces you to use new and new singletons, especially if management is pushing for new features and there is no time for refactoring.

  2. they increase number of states in the system - singletons don't have parametrized constructors - that enforces to use "set" methods which add the necessary context to singletons. But that means that we need to check in singleton methods that the context is correctly set. So again in all the functions we have couple of more "if" statements, if we have "if" statements we probably have to report failure return codes. "hello! here is a singleton which doesn't know its context!".
    Little by little we need to add more and more code which takes care about the state of the system. This doesn't happen during weeks or months. This happens during years of software maintenance. People coming and leaving .. managements is pushing ... do you know the story ? :-)

  3. they are difficult to release - singleton is usually not owned by any other object. Those who are not owned are then released in compiler specific defined order. This is not what we want to have. When there are more singletons they are normally that entangled that graceful release of such objects is not possible. If one cannot gracefully shutdown it's system resource leak analysis is difficult.

There are many reasons and explanations above three are the first which come to my mind just yahoo "why singletons are bad" or something similar to see the consensus.

Žádné komentáře: