After searching different forums related to tight coupling (when a group of classes are highly dependent on one another) Example1
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)
{
}
}
Above class CustomerRepository is dependent on Database class so they are tightly coupled .and i think this class is also an example of Compostion ,then i searched for loose coupling so changing the above class so that tight coupling dependency is removed. Example2
class CustomerRepository
{
private readonly IDatabase database;
public CustomerRepository(IDatabase database)
{
this.database = database;
}
public void Add(string CustomerName)
{
database.AddRow("Customer", CustomerName);
}
}
interface IDatabase
{
void AddRow(string Table, string Value);
}
class Database : IDatabase
{
public void AddRow(string Table, string Value)
{
}
}
I have searched that composition support loose coupling now my question is how example1 is tightly coupled as it were based on composition? secondly what is the relation between loose coupling and composition?
Any help will be greatly appreciated.
What you have there is not really tight coupling. Tight coupling would be this:
class CustomerRepository {
private readonly Database database;
public CustomerRepository() {
this.database = new Database;
}
}
The class has a hardcoded dependency on a specific Database
class which cannot be substituted. That's really tight coupling.
The composition example you're showing is already loosely coupled, since it's entirely possible to substitute the dependency being injected into the constructor by any other Database
inheriting class.
Your second example is even more loosely coupled, since it uses an interface instead of a concrete class; but that's something of a minor detail.