Reputation: 74
I've been using dependency injection, and I noticed that in the constructors (that you are injecting to), the parameters are usually an interface or a base class. I think I understand the reason why the parameters is either interface or base class. However, I realize there are times where the actual class/object that I'm trying to inject could use a method that neither the interface or base class should have (since only the actual class/object I'm instantiating should have that method). But if that's the case, that means I am unable to call that method if the parameters injected is the interface or base class. Should I just create another interface that would contain that method I want on the actual class/object I'm trying to instantiate? I have an example below:
public interface IAnimal
{
void Eat();
}
public abstract class Mammals : IAnimal
{
public void Eat()
{
//eating code
}
public void Sleep()
{
//sleep code
}
}
public class Whale : Mammals
{
public void Swim()
{
//swim code
}
}
public class Dog : Mammals
{
public void Run()
{
//run code
}
}
//Injecting here
public class Class1
{
private readonly Mammals x;
public Class1(Mammals x)
{
this.x = x;
}
public class Method1()
{
x.Eat();
x.Sleep();
//I can't call swim() unless I do below:
//Whale y = x;
//y.Swim();
}
}
I've always thought that using Interface or base class (in depedency injection) allows you to make cleaner code because if I decide to change the class/object I'm injecting, I don't have to make any changes to the codes because whatever object I inject will either have the interface or has the base class. But if I add that code allowing me to use the Swim(), and later decide to inject the Dog class, I would have to change the code to use Run() instead. I'm trying to fully understand dependency injection and the proper way of utilizing it. I've noticed my codes definitely look cleaner because of it. How should I go about the issue of the above code?
Upvotes: 0
Views: 213
Reputation: 415
This is not exactly a dependency injection problem but design question. Dependency injection is for decoupling and allow better unit testing help isolate the client from the impact of design changes or implementation. As for your question you can either call Move() and that should be relevant for all mammals or use iwatermammals as suggested above.
Upvotes: 1
Reputation: 376
If this class is really dealing with any kind of mammal, and you want to make some of them swim, then you can test if the injected object implements ISwim.
For example (mammal as ISwim)?.Swim();
Upvotes: 1