What is the difference between loose coupling and

2018-12-31 10:35发布

Can any one describe the exact difference between loose coupling and tight coupling in Object oriented paradigm?

14条回答
不再属于我。
2楼-- · 2018-12-31 11:02

Loose Coupling is the process of giving the dependency your class needs indirectly without providing all the information of the dependency(i.e in the from of interface) in case tight coupling you directly give in the dependency which is not good way of coding.

查看更多
与君花间醉酒
3楼-- · 2018-12-31 11:05

An extract from my blog post on coupling:

What is Tight Coupling:-

As par above definition a Tightly Coupled Object is an object that needs to know about other objects and are usually highly dependent on each other's interfaces.

When we change one object in a tightly coupled application often it requires changes to a number of other objects. There is no problem in a small application we can easily identify the change. But in the case of a large applications these inter-dependencies are not always known by every consumer or other developers or there is many chance of future changes.

Let’s take a shopping cart demo code to understand the tight coupling:

namespace DNSLooseCoupling
{
    public class ShoppingCart
    {
        public float Price;
        public int Quantity;

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

    public class ShoppingCartContents
    {
        public ShoppingCart[] items;

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

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

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

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

Problems with the above example

Tight Coupling creates some difficulties.

Here, OrderTotal() methods is give us complete amount for the current items of the carts. If we want to add the discount features in this cart system. It is very hard to do in above code because we have to make changes at every class as it is very tightly coupled.

查看更多
登录 后发表回答