Loose Coupling and Tight Cohesion – Walk thru for Design Philosophy

The degree to which the functionality of two modules are related is Coupling. For instance if we have two modules namely A and B, Coupling means ‘B’ must change because ‘A’ changed. Loose Coupling helps is Low code maintenance – We need not make changes to the code again again as modules are almost independent of each other, and change in one wouldn’t trigger change in another.

Strong Coupling is always prohibited.

Following is a highly coupled code:

def get_nums():
    """Get numbers from user"""
    n = input()
    return n
def coupled_add():
    """Get numbers from get_nums() and adds them"""
    n1 = get_nums()
    n2 = get_nums()
    s = n1 + n2
    return s

It is highly coupled because we are using get_nums() in the coupled_add() function. coupled_add() depends on the get_nums, next example shows how to make a loosely coupled function that adds numbers.

"""Both functions are independent of each other"""
def get_numbers(n):
    """Gets numbers from the user"""
    num = input(n)
    return num

def adds(num=[]):
    """Adds numbers or list of numbers"""
    t = 0
    for i in num:
        t += i
    return t

The above two modules are independent of each other and changes in one doesn’t bother the other.

How tightly the responsibilities are related to the module is Cohesion. Is the module performing a specific task. High cohesion is a realization of ‘Single Responsibility’ in SOLID principles. A module with a lot of unrelated responsibilities is low cohesion.

Tight Cohesion is always preferred


You need to bake a muffin, you  need to make the batter, pre-heat oven, oil the molds and fill it will the batter and atlast bake.

#!/usr/bin/env python
def prepair_batter(eggs,oil,milk,flour,sugar):
    """Mixing all the items to a smooth paste"""


def pre_heat(temp):
    """Setting the temperature of the oven """


    print('Temperature set')

def bake():
    """ Adding the batter to the molds and baking"""



So we can see here all the three functions are doing their own jobs, the ‘prepair_batter’ is making the batter, the pre_heat method is preheating the oven. But in the last function bake(), the  ‘count_no_of_guests()’ is not apt, because the responsibility of the bake() is to cook the batter at a specific temperature and not to count guests. The responsibility of the module should be well defines and it should perform the specific actions.

So when you code try having your code loosely coupled and highly cohesive.

One Comment Add yours

Leave a Reply