What is this programming method called? And that's bad?

Recently, in my Unity projects, I found that to create a more modular application, it helps to have a static list in the class that contains links to all or some of the created objects so that they can be easily accessed from other parts of the program. The following is an example:

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... } 

It just allows you to instantiate an object at runtime to add itself to an accessible canvas without having to access it using the findWithTag or findWithType method, which can hurt performance if used too much.

Is this a bad practice or a good one? My colleague believes that this is a one-point programming, but, of course, this is not because it allows you to use and use several objects.

+6
source share
1 answer

This is essentially the Anti Pattern ' service locator , which (surprise) is based on the Singleton Pattern. However, instead of retrieving service instances, you are retrieving object instances.

Regardless of the name, this does NOT actually create a more modular application. On the contrary, you create hard dependencies throughout the application, which makes it difficult to separate it into appropriate components.

Martin Fowler documented the picture pretty well. You can find more information here .
+8
source

Source: https://habr.com/ru/post/989259/


All Articles