What is the difference between loose coupling and tight coupling in the object oriented paradigm?

前端 未结 16 1962
粉色の甜心
粉色の甜心 2020-11-22 08:03

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

16条回答
  •  温柔的废话
    2020-11-22 08:58

    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.

提交回复
热议问题