Monday, April 23, 2018

.net - Get dependencies from a dependency




Let's say I have a PetManager and a Cat:



class PetManager
{
PetManager(IBusinessLayer businessLayer, IWashingService washingService);

IBusinessLayer BusinessLayer;

IWashingService WashingService;
}


class Cat
{
Cat(PetManager manager, string name, int levelOfStupidity);
}


Now let's say that my cat needs the washing service, would it be so baaaaad, to get the dependency from my pet manager ?



class Cat

{
Cat(PetManager manager, string name, int levelOfStupidity)
{
this.manager = manager;
this.name = name;
this.levelOfStupidity = levelOfStupidity;
}

IWashingService WashingService
{

get { return this.manager.WashingService; }
}
}


I strongly suspect that yes, it would be...


Answer



As stated, Cat is a concrete class, so it can expose whatever makes sense. Exposing constructor arguments as read-only properties is a perfectly sensible thing to do.



However, if Cat implemented ICat I would strongly suspect that exposing a dependency like PetManager through ICat would be a leaky abstraction.




In essence, interfaces serve as a sort of access modifier. It makes sense to expose dependencies on the concrete class, but not on the interface. Dependencies are injected through the constructor so can never be part of the interface - the constructor signature is our degree of freedom.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...