Home > Software engineering >  How to create a proper inheritance with dependencies?
How to create a proper inheritance with dependencies?

Time:06-21

While working on my Unity project, I created an abstract class and stored a to reference it as a field. I then called its function Init on Start in order to pass to it its needed references.

So let's say I have an abstract class:

public abstract class Base : MonoBehaviour
{
    protected BaseTool _baseTool; // A references that every inheritor uses
    
    public virtual void Init(BaseTool baseTool)
    {
        _baseTool = baseTool;
    }

    ... // More functuality
}

Now I store it as a field as below:

public class Foo : MonoBehaviour
{
    [SerializeField]
    private Base _base;

    [SerializeField]
    BaseTool _baseTool;

    void Start()
    {
        _base.Init(_baseTool);
    }
}

And now I have an inheritor:

public class Inheritor1 : Base 
{
    public override Init(BaseTool baseTool)
    {
        base.Init(baseTool);
    }

    ... // More functuality
}

So far everything is good. However, let's say I now have another inheritor which also has a dependency on another tool:

public class Inheritor2 : Base 
{
    private Inheritor2Tool _inheritor2Tool; // The dependency
}

That means, that if I want to override Init with Inheritor2 (so I'll be able to call Init in Foo and initialize whatever inheritor is stored inside the field _base) I'll need to change the whole Init signature to Init(BaseTool baseTool, Inheritor2Tool inheritor2Tool) meanwhile only Inheritor2 will use the new parameter Inheritor2Tool inheritor2Tool.

That seems very wrong to me, but I don't know how I can avoid this. So what are my options?

CodePudding user response:

Solution found thanks to the helper below in the comments (thank you very much!). The solution is dependency injection. I'll link 2 videos (one of them provided by the helper) and one tutorial playlist that explain the problem and the solution:

What is dependency injection in Unity?

Zenject (dependency injection framework for Unity) tutorial series.

Zenject (dependency injection framework for Unity) tutorial.

  • Related