Abstractions should not depend upon details. Details should depend upon abstractions?

后端 未结 4 914
离开以前
离开以前 2020-12-13 13:50

In past couple of days, I have read about quite a lot about dependency injection/inversion of control/inversion of dependency. I think that, now my understa

4条回答
  •  星月不相逢
    2020-12-13 14:05

    An interesting case where an abstraction depends on details is when you define an interface that inherits from IDisposable. Take a look at the following abstraction:

    public interface ICustomerRepository : IDisposable
    {
        Customer GetById(Guid id);
        Customer[] GetAll();
    }
    

    Note: IDisposable is an interface specific for .NET, but you can easily imagine your interface containing a Dispose method itself instead of inheriting from such interface.

    It might look convenient for the ICustomerRepository to implement IDisposable. This way any caller can dispose the repository and this way the implementation can dispose the connection or unit of work that it uses internally.

    The interface however is now written with a certain implementation in mind, since it's not obvious at all that all ICustomerRepository implementations would need to clean up any resources. The interface therefore leaks implementation details and therefore violates the Dependency Inversion Principle.

提交回复
热议问题