What is this programming method called? And is it bad?

133 views Asked by At

Lately in my Unity projects, I have discovered that to create a more modular application it helps to have a static List in a class that contains references to all or some of the objects created so that they may be accessed easily from other parts of the program. An example is below:

private static List<Canvas> availableCanvases = new List<Canvas>();

void Start () {
    availableCanvases.Add(this);
}

public static void AddComponentToCanvas(Transform component) {
    for (int i = 0; i < availableCanvases; i++) {
        //Make sure the canvas still exists
        if (availableCanvases[i] != null) {
            component.SetParent(availableCanvases[i]);
            return;
        } else {
            availableCanvases.RemoveAt(i);
            i--;
        }
    }

    //Reached if no canvas found
    //Create new canvas or create error etc...
}

This simply allows an object that is instantiated at runtime to add itself to an available canvas without needing to access it through a findWithTag or findWithType method which will hurt performance if used too much.

Is this bad practice or good? My colleague reckons this represents singleton programming but it of course doesn't because it allows multiple objects to exist and be used.

1

There are 1 answers

3
David L On BEST ANSWER

This is essentially a Service Locator "Anti Pattern" that is (surprise surprise) based around the Singleton Pattern. However, instead of retrieving service instances, you are retrieving object instances.

Regardless of the name, this actually does NOT create a more modular application. On the contrary, you are creating hard dependencies throughout your application that makes it harder to split it apart into the respective components.

Martin Fowler documented the pattern quite well. You can find more information here.