Software Design - Cohesion - with examples


High Cohesion is one of the important aims when your architect and design your software. What is it all about?

You will learn

  • What is Cohesion?
  • Why is Cohesion important?
  • What are the different parts of applications that need high Cohesion?
  • How do we acheive high cohesion?

Software Design

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

What Is Cohesion?

Cohesion is all about grouping related things in your software, together, at one place.

Drawing from a real-life example, there would be a thousand things in your home. But if asked to fetch your tennis racket, you can get it in a matter of minutes, if not seconds. If you are asked to get a cooking utensil, you immediate go the the kitchen. How is it that you are able to retreive things quickly? Because you have organized them in a highly cohesive way. You have put all the related things together.

That is cohesion at play in real life.

Levels Of Cohesion

Cohesion in software is applicable at multiple levels:

  • Methods: We group related methods together to create a class
  • Classes: We group related classes and create a package
  • Packages: We group related packages to probably create a component
  • Components
  • Applications
  • Microservices

Cohesion: A First Example

Have a look at the following code:


	class DownloadAndStore {
		void downloadFromInternet() {
			//...
		}
		void parseData() {
			//...
		}
		void storeIntoDatabase() {
			//...
		}
		void doEverything() {
			downloadFromInternet();
			parseData();
			storeIntoDatabase();
		}
	}

DownloadAndStore has the responsibility of doing three tasks, and has methods to do each one of them:

  • downloadFromInternet() connects to a server and downloads a file
  • parseData() needs an understanding of the data format to get the data from this file
  • saveToDatabase() needs to talk to a database server to save the data

To perform them at one go, it defines another method, aptly named doEverything() to call the other three.

DownloadAndStore is a prime example of a class that has very low cohesion. Each of the listed three methods is doing something totally unrelated to the others.

An Improved Solution

A better solution would be to have an implementation like the following:


	class InternetDownloader {
		public void downloadFromInternet() {
			//...
		}
	}

	class DataParser {
		public void parseData() {
			//...
		}
	}

	class DatabaseStorer {
		public void storeIntoDatabase() {
			//...
		}
	}

	class DownloadAndStore {
		public void doEverything() {
			new InternetDownloader().downloadFromInternet();
			new DataParser().parseData();
			new DatabaseStorer().storeToDatabase();
		}
	}

In this code organization:

  • Classes named InternetDownloader, DataParser and DatabaseStorer are defined, each with a single important thing to do
  • Methods of these classes are invoked to accomplish what is needed, within an external class, DownloadAndStore.

This is a better solution, because it increases the possibilities of code reuse. Let’s explore this a little further.

Layered Architecture And Cohesion

Consider a simple web application, that is organized into three layers:

image info

Organizing an application into layers helps to allocate responsibility clearly and separately. Here,

  • All the UI logic would be confined to the Web layer
  • All the business logic would be the responsibility of the Business layer
  • All the data storage and retrieval would be taken up by the Data layer

This is an example of cohesion at the application layer level. Each layer is highly cohesive, because it does one specific thing, whether large or small.

Component-Level Cohesion

Another instance where cohesion comes into play when you design components to be used in an enterprise application:

image info

Authorization and Authentication approaches might be similar across the microservices in your enterprise. Hence, you could define a common security component. The security component only bothers about whether a given user has the right access and the right credentials - nothing else. It can be easily reused across multiple microservices. It is highly cohesive. It does security and it does it very well.

Note that if you try to enhance the features of the Security component by adding a logging capability as well, then its reusability goes down greatly. Both security and logging are better off implemented separately, as independent cohesive reusable components.

Example: The Spring Framework

One of the best examples of cohesion popularly in use is the Spring Framework:

image info

The framework is not implemented as one big component. It is organized as a set of modules, each one of which can be composed of smaller components. Here is how it is organized, in brief:

  • Core Container: The core feature of Spring is Dependency Injection. This module is composed of core components such as Beans, Core, Context, and SpEL.
  • AOP, Aspects, Instrumentation and Messaging are separate, smaller components
  • The Spring MVC Framework is a separate module with components that handle web application needs
  • The Data Access and Integration module has components such as JDBC, ORM, Transactions and others
  • With the evolution of microservices, Spring Cloud is an additional module that has been designed to contain a set of cohesive components

Leveraging Cohesion In Spring

Each component has its own boundary; it is concerned with taking up a single responsibility, and doing it well. The more cohesive a component is, the more reusable it becomes.

The modular structure of the Spring framework enables a programmer to pull in only those components that she actually needs. If she needs just the core functionality, the Core components sufficient. If database integration is necessary, then she can make use of the JDBC components, for instance.

How To Make Software More Cohesive?

The guiding light that you need to follow to improve the cohesion in your software, is the Single Responsibility Principle (SRP).

When you look at your method/class/package/component, take to a minute to also think about its responsibility. If you can describe it in a single phrase or sentence, then you’ve done a good job defining it.

However, if you end up joining together many phrases and sentences with several “and”s, then you violate the SRP. Your software could end up have low cohesion.

Do check out our video on this:

image info

Summary

In this video, we talked about cohesion in significant detail. Cohesion is all about grouping related things together. Cohesion is applicable at multiple levels in a single application, such as method/class/package/component/application. You group related methods into a class, related classes into a package, and related packages perhaps into a component.

We also examined the fact that cohesive classes and components are highly reusable. In addition, organizing an application into multiple layers also improves their cohesion. Then, we observed how the Spring Framework is organized into cohesive modules, each with a single responsibility. Finally, we looked at how Single Responsibility Principle can be used to build cohesive software.

10 Step Quick Introductions to Frameworks

Related Posts

Spring Boot Tutorials for Beginners

At in28Minutes, we are creating a number of tutorials with videos, articles & courses on Spring Boot for Beginners and Experienced Developers. This resources will help you learn and gain expertise at Spring Boot.

Spring and Spring Boot Video Tutorials for Beginners

At in28Minutes, we are creating a number of tutorials with videos, articles & courses on Spring Boot for Beginners and Experienced Developers. Here's a list of video tutorials and courses for you

Creating Spring Boot and Vue JS CRUD Full Stack Application with Maven

This guide helps you create a full stack application with all the CRUD (Create, Read, Update and Delete) features using Vue JS as Frontend framework and Spring Boot as the backend REST API. We use Maven as the build tool.

Software Design - Separation Of Concerns - with examples

Software architects and programmers love having Seperation of Concerns. What is it? Why is it important? Let's get started.

Object Oriented Software Design - Solid Principles - with examples

Software design is typically complex. Object oriented design takes it to the next level. There are a number of design patterns and other stuff to be aware of. Can we make things simple? What are the goals to aim for when you are doing object oriented design? SOLID Principles is a great starting point for Object Oriented Design.

Software Design - Open Closed Principle - with examples

Open Closed Principle is one of the SOLID Principles. You want your code to be easily extended. How do you achieve it with minimum fuss? Let's get started.

Software Design - What is Dependency Inversion Principle?

Dependency Inversion Principle is one of the important SOLID Principles. Dependency Inversion Principle is implemented by one of the most popular Java frameworks - Spring. What is it all about? How does it help you design good applications?

Introduction to Four Principles Of Simple Design

With agile and extreme programming, the focus is on keeping your design simple. How do you keep your design simple? How do you decide whether your code is good enough?

Software Design - Single Responsibility Principle - with examples

For me, Single Responsibility Principle is the most important design principle. What is Single Responsibility Principle? How do you use it? How does it help with making your software better? Let's get started.

What is an In Memory Database?

In this article, we understand what the term "In-Memory Database" actually means. We see what scenarios they can be used, and why they are important.