'. '

Singleton

From APIDesign

Revision as of 13:28, 23 January 2010 by JaroslavTulach (Talk | contribs)
Jump to: navigation, search

Among other things the Chapter 7 also introduces the NetBeans pattern for doing Component Injection. The claims there are not fully aligned with common know-how of developers that use Dependency Injection. The most surprising thing is that NetBeans APIs commonly contain singletons (and yet it works and supports testability). It is quite common to see static methods like:

public abstract class WindowSystem {
  public static WindowSystem getDefault() { /* some impl */ }
}

This is something a Dependency Injection fan would have never done. Recently Witold Szczerba shared a very interesting observation on our mailing list[1]:

Now I feel totally lost. Jaroslav Tulach and Miško Hevery are, for me,
one of the most prominent and experienced people in the software
engineering, however they proclaim totally contradictory theories
about the bases for building applications. Or they not? I am still
trying to figure it out. In Chapter 7: "Use modular architecture",
Jaroslav describes the concept of generic registry, which is #2 on a
list of  "Top 10 things which make your code hard to test"[2]... Do
we have two mutually exclusive yet both correct theories?

This page is my attempt to explain this paradox. It may not be complete yet, I am still on the hunt for the little differences in initial assumptions that produce such contrary suggestions. But one day we'll get them...

I started by reading the Miško's articles references by Witold. Let's thus use them as headers for now.

Contents

Singletons are Pathological Liars[3]

TBD:

  • describes init code example. Not needed in NetBeans at all.
  • compare. DI suggests to express dependency in constructor. Nb suggests to always provide dummy impl + allow drop in registration (classpath or mock one).
  • mention testing limitations due to levels of [Co-existence]] and solutions
  • point out general problem: this is not only about singletons. Any accessible uninitialized object in system is wrong


Where Have All the Singletons Gone[4]

  • don't mix object construction and app logic
  • rarely call new operation
  • desktop apps have no "request factory", just "application factory"
  • mention Tim's there is only one main window[5]

Root Cause of Singletons[6]

  • private constructor - not the Nb case
  • immutable singleton is OK. If immutable == not configurable, then everything is OK.
  • add story about main window and why NetBeans have just one - again levels of co-existence
  • global state is bad. why? It does not seem that bad in desktop applications...

Top 10 things which make your code hard to test[7]

  • test is small instance of the app
  • Lookup.getDefault() is seam.
  • inherit vs. composition
  • switch vs. polymorphism
  • value objects vs. service objects

Conclusions

Personal tools
buy