1

I have just seen an answer here on SO (What is the difference between loose coupling and tight coupling in the object oriented paradigm?), where the following code was shown to demonstrate tight coupling:

class CustomerRepository
{
    private readonly Database database;

    public CustomerRepository(Database database)
    {
        this.database = database;
    }

    public void Add(string CustomerName)
    {
        database.AddRow("Customer", CustomerName);
    }
}
class Database {
    public void AddRow(string Table, string Value) { }
}

But is that really true? I would say this is an example of constructor injection and therefore not tight coupling at all. Even the article on Wikipedia about DI lists this case, so I do not get why that answer is so upvoted.

John V
  • 4,855
  • 15
  • 39
  • 63
  • 1
    The difference between the examples in the answer you linked is that one depends on a concrete class, while the other depends on an interface. It's not about passing in an object, both examples do that. – reaanb Apr 30 '18 at 15:52
  • @reaanb Yes, but in general, Wikipedia and many other sources show Constructor injection (with an object of class type, not interface) as a form of DI. – John V May 01 '18 at 05:57
  • You're right, but there's no disagreement there. [Wikipedia:Dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) admits that the difference between a class and an interface is a coupling that dependency injection cannot resolve. The SO answer you referenced does address that coupling while using DI in both its examples. DI is a technique that helps us achieve loose coupling by separating object creation from object use, but they're not equal concepts. – reaanb May 01 '18 at 09:01
  • @reaanb Thanks, but I still do not get it. If this is still tight coupling, how DI helped then? – John V May 01 '18 at 09:10
  • See how similar the concrete class and interface examples are in the answer you referenced? That similarity is achievable thanks to DI. Without it, the concrete class example would work with a line such as `this.database = new Database()` but the interface example would break on `this.database = new IDatabase()` since you can't instantiate an interface. By externalizing the instantiation, DI allows us to easily replace a dependency on a concrete class with an interface to achieve loose coupling. – reaanb May 01 '18 at 10:55
  • @reaanb Yes, but again - look at WIkipedia. How the DI helped in those examples of COnstructor injection where the object is simply passed (not interface)? – John V May 02 '18 at 05:05

0 Answers0