Tuesday, April 11, 2006

Singletons and the law of Demeter

To maximize code reuse the law of Demeter should always, atleast, be considered during development.
When this is applied to singleton usage you realize that most users of the singleton doesn't need to
know that they are working on a singleton. Some code:
 
// a singleton
class Foo
{
  static Foo _instance = new Foo();
 
  private Foo() { }
 
  public static Foo Instance { get { return _instance; } }
 
  void DoFoo()
  {
    Console.WriteLine( "Did Foo" );
  }
}
 
// bad user
class Bar
{
  public void DoBar( )
  {
    Foo.Instance.DoFoo();
  }
}
 
With this bad sample user, the Bar class is aware of the fact that the Foo
class is a singleton, if it instead was implemented like this:
 
class GoodBar
{
  public void DoBar( Foo foo )
  {
    foo.DoFoo();
  }
}
 
or
 
class GoodBar2
{
  Foo _foo;
 
  public GoodBar( Foo foo )
  {
    _foo = foo; 
  }
 
  public void DoBar()
  {
    _foo.DoFoo();
  }
}
 
Both "good" users use bar as a normal object and is therefore less tightly coupled to
Foo and they are therefore easier to reuse or exchange / evolve then if they had been
aware of the Foo:s singleton status...

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?