Search code examples
design-patternssolid-principlesdependency-inversion

Is passing object property against Dependency Inversion Principle? Please advise


Assuming there are classes as follow.

interface Book {
  Guid Id { get; }
  Guid AuthorId { get; }
}

interface Author {
  Guid Id { get; }
  void Autograph();
}

Then there are service and data store

interface AutographService {
  void Sign(Guid bookId);
}

interface BookStore {
  Book GetBookById(Guid bookId);
}

Given that the entry point is to call AutographService.Sign(bookId), there are BookStore and AuthorStore injected into AutographService. Does the following data store violate Dependency Inversion Principle?

interface AuthorStore {
  Author GetAuthorById(Guid authorId);
}

And how about the following instead?

interface AuthorStore {
  Author GetAuthorByBookId(Guid bookId);
}

Solution

  • As Dependency inversion principle states:

    • High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).
    • Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.

    Let's see these principles more carefully according your code snippets.

    • High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).

    You are using interfaces. And interface is an abstraction. It is not concrete implementation. So you are okay with this state.

    • Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.

    As your abstraction AuthorStore implements interface interface AuthorStore and you are injecting this abstraction into your service. So it can be concluded that this principle is complied.