Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 660
Luminary Promotions Avatar asked Jun 17 '15 03:06

Luminary Promotions


1 Answers

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.

like image 116
David L Avatar answered Sep 28 '22 02:09

David L