Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best tools for Loose Coupling in C#

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.

like image 407
Tarik Avatar asked Dec 01 '22 11:12

Tarik


2 Answers

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)

like image 53
David Hall Avatar answered Dec 13 '22 18:12

David Hall


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.

like image 40
jason Avatar answered Dec 13 '22 19:12

jason