Sandeep Jaiswal

Loose Coupling

February 27, 2021 | 1 Minute Read

Loose coupling basically means to avoid using implementation types when declaring variables and instead use the interface. Take for example


        public static ArrayList<Integer> getValues(){
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        return numbers;
    }

In the above code instead of using ArrayList we can use List which is the interface that ArrayList implements.

Using interfaces over concrete types is the key for good encapsulation and for loose coupling your code. This is preferred because you decouple your code from the implementation of the list. Using the interface lets you easily change the implementation, ArrayList in this case, to another list implementation without changing any of the rest of the code as long as it only uses methods defined in List.

So we can change it to something like this


       public static List<Integer> getValues(){
        List<Integer> numbers = new LinkedList<>();
        numbers.add(1);
        return numbers;
    }

What we’ve done here is use the interface List as the return type. Using this allows us to change the implementation and use LinkedList instead of a List without breaking out code.