3

Having a larger WinForms application with several classes I currently pass references to several "central" objects around to function calls.

This leads to more method parameters.

Example:

public static class Program
{
    private static MyCentral _central;

    ...
}

...

public class SomeController
{
    public object SomeFunction(MyCentral central) 
    {
        // Do something with the MyCentral instance.
    }
}

Now I'm asking myself whether I should ditch this approach and instead use singletons for those central objects so that everyone can always access these objects and I do not need to pass them around anymore.

Example:

public static class Program
{
    public static MyCentral Central { get; private set; }

    ...
}

...

public class SomeController
{
    public object SomeFunction() 
    {
        // Do something with the Program.Central singleton.
    }
}

My question:

Are there any rules-of-thumb whether the singleton approach or the "passing objects around" approach should be prefered?

Uwe Keim
  • 347
  • 4
  • 13

2 Answers2

6

The rule of thumb is:

Always pass around, never use the traditional singleton pattern approach.

The problem kind of solves itself if you use a dependency injection framework.

Using public statics will make testing harder, strongly couple your components, and make dependencies between your classes harder to see.

Wilbert
  • 1,703
4

Why not

public static class Program
{
    private static MyCentral _central;

    ...
    var controller = new SomeController(_central);
}

...

public class SomeController
{
    MyCentral _central;
    public SomeController(MyCentral myCentral)
    {
        _central=myCentral;
    }


    public object SomeFunction() 
    {
        // Do something with _central
    }
}

This is called "constructor injection". The central object has only to be passed once to your controller, it can be "mocked out" for testing purposes, and if you decide later that you need to have more than one central object, it won't become a problem.

Doc Brown
  • 218,378