Tight Coupling vs Loose Coupling in Java

Tight Coupling vs Loose Coupling in Java

Getting Started

Before Learning any new Tech or Frame Work. first need to understand what is the problem with the current approach and how the frame work is going to change the approach to a solution.

In this blog will mainly focus on why spring such powerful framework for java and what are the features of the spring framework.

First will check what is the difference between tight coupling and loose coupling.

Difference Between Tight coupling and loose coupling

Let's take example of Binary Search Algorithm as an example.

Binary search is an algorithm Searching Algorithm. which searches for an target element in array of elements. To search an element in an array for BinarySearch algorithm there is a pre condition that array hast to be sorted.

Tight Coupling

public class BubbleSort {
    public int[] sort(int[] arr) {
        //sort the array and returns the sorted arr
        return arr;
    }
}
public class SelectionSort {
    public int[] sort(int[] arr) {
        //sort the array and returns the sorted arr
        return arr;
    }
}
public class BinarySearch {
  private BubbleSort bubblesort = new BubbleSort();
  // Binary Search can use either bubblesort or selectionsor to sort an array
  // private SelcectionSort selectionSort = new SelectionSort();

  public int binarySearch(int[] arr,int target) {
      //Sorts the array of integers using bubblesort
      //performs algorithm
      //return index of the target
      //if element is not found then return -1;
      return -1;
  }
}

Loose Coupling

public interface SortAlgorithm {
    public int[] sort(int[] numbers);
}
public class BubbleSort implements SortAlgorithm {
       public int[] sort(int[] arr) {
        //sort the array and returns the sorted arr
        return arr;
    }
}
public class SelectionSort implements SortAlgorithm {
       public int[] sort(int[] arr) {
        //sort the array and returns the sorted arr
        return arr;
    }
}
public class BinarySearch {
  private SortAlgorithm bubblesort = new BubbleSort();

  public int binarySearch(int[] arr,int target) {
      // sorts the array here it can either use bubble sort or selection 
      //performs algorithm
      //return index of the target
      //if element is not found then return -1;
      return -1;
  }
}

In next Article will see some Terminology for Spring Framework. Stay in Touch .....