I was reading Loose Coupling and its benefits which are really good stuff but I started wondering which tools are great to create loosely-coupled solutions ? First what came to my mind are Type and Interfaces and Abstract classes but I am sure there are so many ways to provide loose coupling. Maybe Polymorphism helps to create loosely-coupled objects and systems.
Thanks.
This is a very broad question - possibly too broad to answer.
However, two methodologies that can provide a solution with "loose coupling" are:
Dependency Injection
Dependency Injection (especially when using an Inversion of Control Container) provides loose coupling within an application or solution - With dependency injection you do not hard code your references to dependent objects, instead you code to interfaces and inject implementations of those interfaces.
Here is a quick code example of a Logging component of an application, that implements an ILogger interface
public class ConcreteLogger : ILogger
{
public LogMessage(string message)
{
Log.Write(message);
}
}
One of your classes then receives this concrete implementation of the logger interface.
public class MyClass
{
private ILogger logger;
public myClass(ILogger logger)
{
this.logger = logger;
}
public void DoSomething()
{
// Now if DoSomething needs to call logging it can call what ever ILogger was passed in
this.logger.Log("We did something");
}
}
Service Orientation
Service Orientation provides loose coupling between different subsystems of a solution - With Service Orientation each part of a solution becomes its own stand alone services that publishes and interfaces (often a messaging based interface).
This means that an application when needing for example to talk to the Shipping subsystem of a solution only needs to know about the systems interfaces and its address, and does not need to know anything about its internal implementation. This can almost be seen as a broader application of basic OO principles.
Both of these provide two different types of loose coupling (that is one of the problems with your question, the term it self is loosely defined)
Others have already provided great answers but I want to add one thought: polymorphism as implemented using inheritance does not promote loose-coupling. Inheritance is a very strong coupling between base classes and derived classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With