popsiporkkanaa
popsiporkkanaa

Reputation: 748

Dependency injection results with unnecessary implementation

I am creating an Animal class which implements IAnimal interface. Then, both Cats and Dogs classes implement IAnimal interface. Currently I keep only 3 simple methods inside IAnimal for short demonstration. The main class Animals is constructed by using Dependency Injection (DI).

When IAnimal has more methods, for example: Cats class only implements SomethingOnlyCatsDo method, Dogs class implements SomethingOnlyDogsDo method, then there will be more unnecessary implementations inside each of those classes (like Cats().CatchDisk() or Dogs().CatchMouse() in current example).

My question is, is there any way which can help me keep using DI but avoid this growing of unnecessary implementations?

public interface IAnimal
{
    void Sound();
    void CatchMouse();
    void CatchDisk();

    // What if there are more methods here
    //string GetOwnerName();
    //void SomethingOnlyCatsDo();
    //void SomethingOnlyDogsDo();
}

public class Cats : IAnimal
{
    public void Sound()
    {
        Console.WriteLine("Meow meow");
    }

    public void CatchMouse()
    {
        Console.WriteLine("Catching mouse");
    }

    public void CatchDisk()
    {
        throw new NotImplementedException();
    }
}

public class Dogs : IAnimal
{
    public void Sound()
    {
        Console.WriteLine("Woof woof");
    }

    public void CatchDisk()
    {
        Console.WriteLine("Catching disk");
    }

    public void CatchMouse()
    {
        throw new NotImplementedException();
    }
}

// Main class
public class Animals
{
    private readonly IAnimal _animal;

    public Animals(IAnimal animal)
    {
        _animal = animal;
    }

    public void Sound()
    {
        _animal.Sound();
    }

    public void CatchADisk()
    {
        _animal.CatchDisk();
    }

    public void CatchAMouse()
    {
        _animal.CatchMouse();
    }
}

Upvotes: 0

Views: 248

Answers (2)

Thadeu Fernandes
Thadeu Fernandes

Reputation: 505

You can use Interface Segregation Principle.

The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.

Your IAnimal interface will only have Sound(), then you make a new interface called ICat that inherits from IAnimal and this interface will have CatchMouse(). Your class Cats will inherit from ICat.

Here's a practical example.

Upvotes: 2

Koja
Koja

Reputation: 900

If following SOLID principles, and especially the I (Interface Segregation, https://en.wikipedia.org/wiki/Interface_segregation_principle), IAnimal should not have CatchDisk or CatchMouse methods. Instead you should have IAnimal with the Sound() method, and separate interfaces ICatchesMouse and ICatchesDisk. This way no Animal has to implement unnecessary methods.

Upvotes: 3

Related Questions