Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "loose coupling?" Please provide examples

People also ask

What is loose coupling with example?

Example 1: Imagine you have created two classes, A and B, in your program. Class A is called volume, and class B evaluates the volume of a cylinder. If you change class A volume, then you are not forced to change class B. This is called loose coupling in Java.

What is loose coupling and why should we use it?

Loose coupling is a design goal to reduce the inter-dependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component.

What is loose coupling and how does it compare to tight coupling give examples of technologies that use tight and loose coupling?

Tight Coupling means one class is dependent on another class. Loose Coupling means one class is dependent on interface rather than class. In tight coupling, there are hard-coded dependency declared in methods. In loose coupling, we must pass dependency externally at runtime instead of hard-coded.

What do you mean by loose coupling in spring?

Loose coupling - When an object gets the object to be used from the outside, then it is a loose coupling situation. As the main object is merely using the object, this object can be changed from the outside world easily marked it as loosely coupled objects.


Consider a simple shopping cart application that uses a CartContents class to keep track of the items in the shopping cart and an Order class for processing a purchase. The Order needs to determine the total value of the contents in the cart, it might do that like so:

Tightly Coupled Example:

public class CartEntry
{
    public float Price;
    public int Quantity;
}

public class CartContents
{
    public CartEntry[] items;
}

public class Order
{
    private CartContents cart;
    private float salesTax;

    public Order(CartContents cart, float salesTax)
    {
        this.cart = cart;
        this.salesTax = salesTax;
    }

    public float OrderTotal()
    {
        float cartTotal = 0;
        for (int i = 0; i < cart.items.Length; i++)
        {
            cartTotal += cart.items[i].Price * cart.items[i].Quantity;
        }
        cartTotal += cartTotal*salesTax;
        return cartTotal;
    }
}

Notice how the OrderTotal method (and thus the Order class) depends on the implementation details of the CartContents and the CartEntry classes. If we were to try to change this logic to allow for discounts, we'd likely have to change all 3 classes. Also, if we change to using a List<CartEntry> collection to keep track of the items we'd have to change the Order class as well.

Now here's a slightly better way to do the same thing:

Less Coupled Example:

public class CartEntry
{
    public float Price;
    public int Quantity;

    public float GetLineItemTotal()
    {
        return Price * Quantity;
    }
}

public class CartContents
{
    public CartEntry[] items;

    public float GetCartItemsTotal()
    {
        float cartTotal = 0;
        foreach (CartEntry item in items)
        {
            cartTotal += item.GetLineItemTotal();
        }
        return cartTotal;
    }
}

public class Order
{
    private CartContents cart;
    private float salesTax;

    public Order(CartContents cart, float salesTax)
    {
        this.cart = cart;
        this.salesTax = salesTax;
    }

    public float OrderTotal()
    {
        return cart.GetCartItemsTotal() * (1.0f + salesTax);
    }
}

The logic that is specific to the implementation of the cart line item or the cart collection or the order is restricted to just that class. So we could change the implementation of any of these classes without having to change the other classes. We could take this decoupling yet further by improving the design, introducing interfaces, etc, but I think you see the point.


Many integrated products (especially by Apple) such as iPods, iPads are a good example of tight coupling: once the battery dies you might as well buy a new device because the battery is soldered fixed and won't come loose, thus making replacing very expensive. A loosely coupled player would allow effortlessly changing the battery.

The same goes for software development: it is generally (much) better to have loosely coupled code to facilitate extension and replacement (and to make individual parts easier to understand). But, very rarely, under special circumstances tight coupling can be advantageous because the tight integration of several modules allows for better optimisation.


I'll use Java as an example. Let's say we have a class that looks like this:

public class ABC
{
   public void doDiskAccess() {...}
}

When I call the class, I'll need to do something like this:

ABC abc = new ABC();

abc. doDiskAccess();

So far, so good. Now let's say I have another class that looks like this:

public class XYZ
{
   public void doNetworkAccess() {...}
}

It looks exactly the same as ABC, but let's say it works over the network instead of on disk. So now let's write a program like this:

if(config.isNetwork()) new XYZ().doNetworkAccess();
else new ABC().doDiskAccess();

That works, but it's a bit unwieldy. I could simplify this with an interface like this:

public interface Runnable
{
    public void run();
}

public class ABC implements Runnable
{
   public void run() {...}
}

public class XYZ implements Runnable
{
   public void run() {...}
}

Now my code can look like this:

Runnable obj = config.isNetwork() ? new XYZ() : new ABC();

obj.run();

See how much cleaner and simpler to understand that is? We've just understood the first basic tenet of loose coupling: abstraction. The key from here is to ensure that ABC and XYZ do not depend on any methods or variables of the classes that call them. That allows ABC and XYZ to be completely independent APIs. Or in other words, they are "decoupled" or "loosely coupled" from the parent classes.

But what if we need communication between the two? Well, then we can use further abstractions like an Event Model to ensure that the parent code never needs to couple with the APIs you have created.


Sorry, but "loose coupling" is not a coding issue, it's a design issue. The term "loose coupling" is intimately related to the desirable state of "high cohesion", being opposite but complementary.

Loose coupling simply means that individual design elements should be constructed so the amount of unnecessary information they need to know about other design elements are reduced.

High cohesion is sort of like "tight coupling", but high cohesion is a state where design elements that really need to know about each other are designed so that they work together cleanly and elegantly.

The point is, some design elements should know details about other design elements, so they should be designed that way, and not accidentally. Other design elements should not know details about other design elements, so they should be designed that way, purposefully, instead of randomly.

Implementing this is left as an exercise for the reader :) .


Tightly coupled code relies on a concrete implementation. If I need a list of strings in my code and I declare it like this (in Java)

ArrayList<String> myList = new ArrayList<String>();

then I'm dependent on the ArrayList implementation.

If I want to change that to loosely coupled code, I make my reference an interface (or other abstract) type.

List<String> myList = new ArrayList<String>();

This prevents me from calling any method on myList that's specific to the ArrayList implementation. I'm limited to only those methods defined in the List interface. If I decide later that I really need a LinkedList, I only need to change my code in one place, where I created the new List, and not in 100 places where I made calls to ArrayList methods.

Of course, you can instantiate an ArrayList using the first declaration and restrain yourself from not using any methods that aren't part of the List interface, but using the second declaration makes the compiler keep you honest.


The degree of difference between answers here shows why it would be a difficult concept to grasp but to put it as simply as I can describe it:

In order for me to know that if I throw a ball to you, then you can catch it I really dont need to know how old you are. I dont need to know what you ate for breakfast, and I really dont care who your first crush was. All I need to know is that you can catch. If I know this, then I dont care if its you I am throwing a ball to you or your brother.

With non-dynamic languages like c# or Java etc, we accomplish this via Interfaces. So lets say we have the following interface:

public ICatcher
{
   public void Catch();
}

And now lets say we have the following classes:

public CatcherA : ICatcher
{
   public void Catch()
   {
      console.writeline("You Caught it");
   }

}
public CatcherB : ICatcher
{
   public void Catch()
   {
      console.writeline("Your brother Caught it");
   }

}

Now both CatcherA and CatcherB implement the Catch method, so the service that requires a Catcher can use either of these and not really give a damn which one it is. So a tightly coupled service might directly instantiate a catched i.e.

public CatchService
{
   private CatcherA catcher = new CatcherA();

   public void CatchService()
   {
      catcher.Catch();
   }

}

So the CatchService may do exactly what it has set out to do, but it uses CatcherA and will always user CatcherA. Its hard coded in, so its staying there until someone comes along and refactors it.

Now lets take another option, called dependency injection:

public CatchService
{
   private ICatcher catcher;

   public void CatchService(ICatcher catcher)
   {
      this.catcher = catcher;
      catcher.Catch();
   }
}

So the calls that instantiate CatchService may do the following:

CatchService catchService = new CatchService(new CatcherA());

or

CatchService catchService = new CatchService(new CatcherB());

This means that the Catch service is not tightly coupled to either CatcherA or CatcherB.

There are several other strategies for loosely coupling services like this such as the use of an IoC framework etc.