Software Design - What is Dependency Inversion Principle?


NEW COURSE RELEASED! - 21 HOURS, 200+ VIDEOS - Master DevOps with Docker, Kubernetes and Azure DevOps


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?

You will Learn

  • What is Dependency Inversion Principle?
  • How are Dependency Inversion Principle and Spring Framework related?
  • A few examples of Dependency Inversion Principle in action

Free Courses - Learn in 10 Steps

Software Design Principles

This is the last article in a series of articles on important Software Design Principles:

What Is Dependency Inversion principle (DIP)?

“Depend Upon Abstractions (interfaces), not Implementations (concrete classes)”

What does this statement mean? Let’s try understanding that with an example:

Let’s look at an example of what this means:


abstract class OutputDevice {
	void copy(String device) {
		Keyboard keyboard = new Keyboard();
		int character;
		while ((character = keyboard.read()) != -1) {
			if (device.equals("Printer")) {
				writeToPrinter(character);
			} else {
				writeToDevice(character);
			}
		}
	}

	private void writeToDevice(int character) {
		// TODO Auto-generated method stub
		
	}

	private void writeToPrinter(int c) {
		// TODO Auto-generated method stub
		
	}
}


What does the copy() method do?

It reads a character from the keyboard, and then decides where this character needs to go. If it’s a printer, write to the printer. Else, send it to the disk.

The problem here is that as the number of OutputDevice types increase, the logic of copy() needs to change every single time.

Let’s look at an alternate implementation:


	public interface Reader {
		public char read();
	}

	public interface Writer {
		public void write(char ch);
	}

	void copy(Reader r, Writer w) {
		int c;

		while((c = r.read()) != EOF) {
			w.write(c);
		}
	}

What we have done here is define two separate interfaces, one to provide the read(), and the other to define the write() methods.

The responsibility of the copy() method is quite clear here: it reads from the Reader interface, and writes whatever it gets to the Writer interface.

copy() now focuses only on the actual operation, and it does so by identifying everything else as its dependencies.

It can now work with any implementation of Reader and Writer interfaces.

DIP and The Spring Framework

DIP is one of the core principles that the Spring Framework enables. Have a look at this example:


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

			//...
		}
	}

BinarySearchImpl directly creates an instance of the BubbleSortAlgorithm. Note that BubbleSortAlgorithm is a dependency of BinarySearchImpl, and as we saw in our previous example, directly accessing it is not a great idea. If you want to switch from a bubble-sort to a quicksort algorithm later, you need to change quite a lot of code inside BinarySearchImpl.

Better Approach for BinarySearchImpl is to make use of an interface - sort algorithm. Here is how our modified code would look like:


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

	@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);
			//...
		}
	}

User of the BinarySearchImpl class, can also pass in a specific implementation of SortAlgorithm, such as a bubble-sort or a quick-sort implementation.

BinarySearchImpl is decoupled from which SortAlgorithm to use.

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

By applying the DIP, you make your code more testable. The test code could pass in dependency mocks to properly test the code.

Do check out our video on this:

image info

Summary

Dependency Inversion is about identifying dependencies and externalizing them. You can use a framework like Spring to simplify Dependency Inversion. DIP makes your code more maintainable, reusable and testable.

What to Learn Next?

NEW COURSE RELEASED! - 21 HOURS, 200+ VIDEOS - Master DevOps with Docker, Kubernetes and Azure DevOps


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


85,000 Subscribers are learning from our Free Videos on YouTube : JSP Servlets, Spring, Spring Boot, Spring MVC, Hibernate, Eclipse, Maven, JUnit, Mockito, Full Stack - React, Full Stack - Angular, Docker, Kubernetes, AWS, AWS Fargate, PCF and Azure


Here are the recommend articles to read next : Spring Interview Questions, Spring Boot Interview Questions, Microservices, Hibernate, Spring Security, REST API with Spring Boot, Full Stack with React, SOAP Web Services, Exception Handling, Embedded Servers, Spring Data Rest, Spring vs Spring MVC vs Spring Boot, Building Web Application and Spring Data JPA. You can checkout all our 100+ articles here - All Articles.


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


Related Posts

Docker Tutorial for Beginners - with Java and Spring Boot

Learn about Docker - What is Docker? Why Is Docker Popular? How to create Docker Image for a Java Spring Boot App?

Devops Tutorial | DevOps with Docker, Kubernetes and Azure DevOps

What is DevOps? How is it different from Agile? What are the popular DevOps Tools? What is the role of Docker, Kubernetes and Azure DevOps in DevOps. Let's get started with a simple usecase.

Deploy Java Spring Boot Applications to AWS, Azure, GCP with Docker and Kubernetes

In this article, we focus our attention on the cloud. How to learn the cloud and deploy Java Spring Boot Applications to AWS, Azure, GCP with Docker and Kubernetes?

Microservices Architectures - Non Functional Requirements - Performance

In this article, we explore an important non functional requirement called performance.

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.

Microservices with Spring Boot and Java - Part 1 - Getting Started

Let's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. In part 1 of this series, lets get introduced to the concept of microservices and understand how to create great microservices with Spring Boot and Spring Cloud.

20+ Spring Boot Projects with Code Examples

At in28Minutes, we have created more than 20 projects with code examples on Github. We have 50+ articles explaining these projects. These code examples will you learn and gain expertise at Spring Boot.

REST API Best Practices - With Design Examples from Java and Spring Web Services

Designing Great REST API is important to have great microservices. How do you design your REST API? What are the best practices?

Index - 500+ Videos

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