Software Design - Coupling - with examples


Image


Software architects and programmers love low coupling. What is coupling? Why is coupling important? Let’s get started.

You will learn

  • What is coupling?
  • What are common examples of coupling in software?
  • How can we reduce the amount of coupling between classes, between components, and the like?

Free Courses - Learn in 10 Steps

Software Design

This is the fifth article in a series of articles on Software Design:

Example of Couping

Let’s start with an example.

Let’s say a friend of mine is developing a Java component, in the form of a JAR file, for me to use. However, there is an implicit constraint imposed here - I need to use Java (or a JVM Based language) to use the utility JAR file! In other words, developing the component as a Java JAR has coupled me to using Java as well. To break free, I need to decouple.

How to Decouple? An Example:

Instead of providing me with a JAR, I could ask my friend to create a web service interface for me to access the same functionality. The concept would look something like this:

image info

The web service is created around the JAR, and can be accessed from a Java, a PHP, or a .NET application. We can use any kind of application to invoke the web service.

This implies we have effectively decoupled from the underlying technology of the component. We are no longer affected by the fact that the component was developed in Java.

Another Example for Low Coupling - Spring Framework

Spring Framework has a highly modular structure:

image info

Suppose we want to use a specific module from this framework; for instance, the Spring JDBC module.

What would happen if Spring tells you that you can only use Spring JDBC if you also use the Beans and Context modules?

You would probably not use it at all, because it introduces additional dependencies such as configuration etc.

Spring does get this right; it does not force you to use Beans or Context along with JDBC. In other words, Spring modules are not coupled with the other ones.

Class-level coupling - The Order class

Let’s now go one level deeper. Let’s look at Coupling at the level of classes.

Let’s look at a simple shopping cart example:


	class ShoppingCartEntry {
		public float price;
		public int quantity;
	}

	class ShoppingCart {
		public ShoppingCartEntry[] items;
	}

	class Order {
		private ShoppingCart cart;
		private float salesTax;

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

		public float orderTotalPrice() {
			float cartTotalPrice = 0;

			for(int i=0; i<cart.items.length; i++) {
				cartTotalPrice += cart.items[i].price * cart.items[i].quantity;
			}
			cartTotalPrice += cartTotalPrice * salesTax;
			return cartTotalPrice;
		}
	}

You would observe that orderTotalPrice() knows the internal details of the ShoppingCart and ShoppingCartEntry classes:

  • It accesses the items field of ShoppingCart directly
  • It accesses the price and quantity fields of ShoppingCartEntry, also directly

Scenario : Try and imagine a situation where we change the name of the price field of ShoppingCartEntry, to something else.

Approach : Code within orderTotalPrice() would also need to change.

If you change the type of the items array (possibly to a list) within ShoppingCart, that would also lead to a change within orderTotalPrice().

Order class is tightly coupled to the ShoppingCart and ShoppingCartEntry classes.

How do we decouple them?

Decoupling the Order class Example

Here is one way of achieving this:


	class ShoppingCartEntry {
		float price;
		int quantity;

		public float getTotalPrice() {
			return price*quantity;
		}
	}

	class CartContents {
		ShoppingCartEntry[] items;

		public float getTotalPrice() {
			float totalPrice = 0;

			for(ShoppingCartEntry item:items) {
				totalPrice += item.getTotalPrice();
			}
			return totalPrice;
		}
	}

	class Order {
		CartContents cart;
		float salesTax;

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

		public float totalPrice() {
			return cart.getTotalPrice * (1.0f + salesTax);
		}
	}

Note the following points:

  • Instead of making the price and quantity fields accessible, ShoppingCartEntry now makes a method named getTotalPrice() available to CartContents.
  • The CartContents class does something very similar, by also providing a getTotalPrice() method for Order to use.
  • The Order class now only invokes the getTotalPrice() methhod exposed by CartContents, to compute the total cart value in totalPrice().

Now,

  • If the price field in ShoppingCartEntry has its name changed, only getTotalPrice() within the same class would be affected
  • If the type of items within CartContents is changed from an array to a list, again only the CartContents getTotalPrice() method needs to be altered.
  • The code within Order is not affected by either of these changes at all.

We have now completely decoupled Order from both ShoppingCartEntry and CartContents.

Another Coupling Example with Spring Framework

Consider the following body of code:


	public class BinarySearchImpl {
		public int binarySearch(int[] numbers, int numberToSearchFor) {
			BubbleSortAlgorithm bubbleSortAlgorthm = new BubbleSortAlgorithm();
			int[] sortedNumbers = bubbleSortAlgorithm.sort(numbers);

			//...
		}
	}

You would notice that the BinarySearchImpl class is directly dependent on the BubbleSortAlgorithm class. If we need to change the actual sort algorithm, to use quicksort for instance, then a lot of code within BinarySearchImpl needs to change.

We can solve this issue by making use of interfaces. Here is how our modified code would look like:


	public intrface SortAlgorithm {
		public int[] sort(int[] numbers);
	}

If you use the Spring framework, you could use the @Autowired annotation with the BinarySearchImpl class, to automatically fetch an implementation of an available sort algorithm:


	@Component
	public class BinarySearchImpl {
		@Autowired
		private SortAlgorithm sortAlgorithm;

		public BinarySearchImpl(SortAlgorithm sortAlgorithm) {
			super();
			this.sortAlgorithm = sortAlgorithm;
		}

		public int[] binarySearch(int[] numbers, int numberToSearchFor) {
			int[] sortedNumbers = sortAlgorithm.sort(numbers);
			//...
		}
	}

What we have achieved here is reduce the coupling between BinarySeacrhImpl and a specific sort algorithm.

A Practical Viewpoint of Coupling

A good way of thinking about coupling, is if you change the inner details of a class or a component, do you need to make changes elsewhere as well?

Such dependencies are not desirable. If you intend to reuse code from one place to another, the related dependencies should be as few as possible.

Coupling can occur at multiple levels in an application:

  • Class-level
  • API-level
  • Component-level

Let’s look at an example of coupling at component level:

Component-Level Coupling

Consider the following organization of an enterprise web application:

image info

If the Security component were coupled with the Logging component, then wherever we need Security, we would also need to access Logging. That’s not good.

Coupling With Layers

Let’s look at an example of a layered web application:

image info

It is organized into these three layers. Also assume that from the Web layer Controller, I need to call multiple methods from the Business layer. Let’s say five different methods need to be called for a single such requirement. This is a clear case of coupling.

A very effective way to avoid such layer-to-layer coupling is to use the Facade Pattern. You can create a Facade component on top of the Business layer, that manages calls to these five methods. The web layer can then make do with calling a single method from the Facade component.

All in all, decoupling makes the code more reusable and testable.

Do check out our video on this:

image info

Summary

In this article, we looked at the concept of coupling at multiple levels: at the class, the component, the API and the layer level. We also looked at how to get around this factor through decoupling, at each of these levels. We identified the key question to ask about coupling: “If something changes at a particular place, would other things need to change as well? And If I use something, would I be forced to use something else as well?”

Best Selling Udemy Courses

Image
Image Image Image Image Image Image Image Image Image

Join 450,000 Learners and 30+ Amazing Courses

350,000 Learners are learning everyday with our Best Selling Courses : Spring Boot Microservices, Spring, Spring Boot, Web Services, Hibernate, Full Stack React, Full Stack Angular, Python, Spring Interview Guide, Java Interview, Java Functional Programming, AWS, Docker, Kubernetes, PCF, AWS Fargate and Azure


Do not know where to start your learning journey? Check out our amazing learning paths:
Learning Path 01 - Spring and Spring Boot Web Applications and API Developer,
Learning Path 02 - Full Stack Developer with Spring Boot, React & Angular,
Learning Path 03 - Cloud Microservices Developer with Docker and Kubernetes,
Learning Path 04 - Learn Cloud with Spring Boot, AWS, Azure and PCF and
Learning Path 05 - Learn AWS with Microservices, Docker and Kubernetes


Subscribe

FREE COURSES



Related Posts

Writing Integration Tests for Rest Services with Spring Boot

Setting up a basic REST Service with Spring Boot is a cake walk. We will go one step further and add great integration tests!

Integrating Spring Boot and Spring JDBC with H2 and Starter JDBC

Learn using Spring Boot Starter JDBC to connect Spring Boot to H2 (in memory database) using Spring JDBC. You will create a simple project with Spring Boot. You will add code to the project to connect to a database using Spring JDBC. You will learn to implement the basic CRUD methods.

JUnit Tutorial for Beginners in 5 Steps

JUnit Tutorial for Beginners in 5 Steps. Setting up a basic JUnit example and understanding the basics of junit.

JPA and Hibernate Tutorial For Beginners - 10 Steps with Spring Boot and H2

JPA and Hibernate in 10 Steps with H2 - Setting up a basic project example with Spring Boot and in memory database H2. Its a cake walk.

Spring Boot Tutorial For Beginners in 10 Steps

Introduction to Spring Boot in 10 Steps. Learn the basics of Spring Boot setting up a basic project example with Spring Boot.

Spring Framework Tutorial for Beginners - Your First 10 Steps

Learn the basics of Spring Framework setting up a very simple example.

JPA and Hibernate Tutorial using Spring Boot Data JPA

Complete journey starting from JDBC to JPA to Spring Data JPA using an example with Spring Boot Data JPA starter project. We use Hibernate as the JPA Implementation.

Creating a Web Application with Spring Boot with JSP

Setting up a basic web application with Spring Boot is a cake walk. We will create a simple web application using Spring Initializr and add JSP features to it.

What is Spring Boot Auto Configuration?

Auto Configuration is the most important feature in Spring Boot. In this tutorial, we will learn important concepts about Auto Configuration with a couple of examples.

Unit Testing Rest Services with Spring Boot and JUnit

Setting up a Basic REST Service with Spring Boot is a cake walk. We will go one step further and add great unit tests to our RESTful Service.


Search