Design Patterns – Is Dependency Inversion Principle Necessary?

dependency-inversion

I've read a lot about dependency inversion principle but still, I can't apply it to my case. I just don't know when I should apply it and when not. I write a simple application in Java to generate invoices. For now, I have basic classes: Client, Product, InvoiceLine and Invoice. Should these classes communicate through interfaces? For instance, I have a method in Product for getting name of the product:

public String getName() {
    return name;
}

And I use this method in class Invoice

public void addLineToInvoice(Product product, int quantity) {
    rows.add(new InvoiceLine(rows.size(), product.getName(), quantity, product.getPrice()));
}

Now, should I create an interface for Product? Or is it unnecessary?

Best Answer

(Disclaimer: I understand this question as "applying the Dependency Inversion Principle by injecting objects through interfaces into other object's methods", a.k.a "Dependency Injection", in short, DI.)

Programs were written in the past with no Dependency Injection or DIP at all, so the literal answer to your question is obviously "no, using DI or the DIP is not necessary".

So first you need to understand why you are going to use DI, what's your goal with it? A standard "use case" for applying DI is "simpler unit testing". Refering to your example, DI could make sense under the following conditions

  • you want to unit test addLineToInvoice, and

  • creating a valid Product object is a very complex process, which you do not want to become part of the unit test (imagine the only way to get a valid Product object is to pull it from a database, for example)

In such a situation, making addLineToInvoice accept an object of type IProduct and providing a MockProduct implementation which can be instantiated simpler than a Product object could be a viable solution. But in case a Product can be easily created in-memory by some standard constructor, this would be heavily overdesigned.

DI or the DIP are not an end in itself, they are a means to an end. Use them accordingly.

Related Topic