0

According to the definition by Robert Martin, high level modules should not depend on low level modules, instead both should depend on abstractions.

So if I have a domain entity Invoice that uses an interface InvoiceRepository for persistence, and an infrastructure layer where this interface is implemented in a class PdoInvoiceRepository, then both modules - the entity and the persistence mechanism - depend on the abstraction (interface)?

Further, if the methods in above interface do not depend on the implementation details but instead express the abstracted needs of my domain model, then I have achieved dependency inversion?

Robert Harvey
201k55 gold badges469 silver badges682 bronze badges
asked Jun 7, 2021 at 13:40

1 Answer 1

2

The idea behind dependency inversion is to prevent hard-coded dependencies within a class.

If I write this:

public class Customer
{
 private CustomerRepository _repository;
 
 public Customer()
 {
 _repository = new CustomerRepository();
 }
}

Then I have tightly bound CustomerRepository to Customer.

But if, instead, I write

public class Customer
{
 private ICustomerRepository _repository
 public Customer(ICustomerRepository repository)
 {
 _repository = repository;
 }
}

I can then write:

var customer = new Customer(new RepositoryClassThatImplementsICustomerRepository());

So you can hand the constructor of my class any object that implements the ICustomerRepository interface. The class is no longer tightly-coupled to a specific implementation of Customer Repository.

ICustomerRepository is an abstraction; it defines the operations that are valid for a repository object that satisfies Customer's requirements.

answered Jun 7, 2021 at 14:53
2
  • So far, so clear. What about the second part of the definition which states that abstractions should not depend on details. My interpretation is that the interface methods should express what my higher level module needs, so the class that implements said interface should be modeled to fit the abstraction. Commented Jun 7, 2021 at 15:09
  • softwareengineering.stackexchange.com/q/64932/1204 Commented Jun 7, 2021 at 15:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.