DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Application Architecture Design Principles
  • Is Podman a Drop-in Replacement for Docker?
  • Explainable AI: Making the Black Box Transparent
  • Incident Response Guide

Trending

  • Application Architecture Design Principles
  • Is Podman a Drop-in Replacement for Docker?
  • Explainable AI: Making the Black Box Transparent
  • Incident Response Guide
  1. DZone
  2. Coding
  3. Frameworks
  4. Software Design in Java: What Is the Dependency Inversion Principle?

Software Design in Java: What Is the Dependency Inversion Principle?

DIP makes your code more maintainable, reusable, and testable.

Ranga Karanam user avatar by
Ranga Karanam
CORE ·
Oct. 02, 19 · Presentation
Like (5)
Save
Tweet
Share
9.93K Views

Join the DZone community and get the full member experience.

Join For Free

Dependency Inversion Principle

DIP makes your code more maintainable, reusable, and testable.

Dependency Inversion Principle is one of the important SOLID principles. And the Dependency Inversion Principle is implemented in one of the most popular Java frameworks — Spring. So, what is it all about? And how does it help you design better applications?

You may also like: SOLID Principles: Dependency Inversion Principle

What You Will Learn

  • What is the Dependency Inversion Principle?
  • How is the Dependency Inversion Principle and Spring Framework related?
  • Examples of the Dependency Inversion Principle in action

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, it writes to the printer. Otherwise, it sends 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 Readerinterface and writes whatever it gets to the Writerinterface.

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 enabled by the Spring Framework. 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.

A better approach for BinarySearchImpl is to make use of an interface — sort algorithm. Here is what 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);
//...
}
}


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

In conclusion, here are a few important things to note:

  • 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.

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.

Lastly, do check out our video on this:


Further Reading

SOLID Principles: Dependency Inversion Principle

Design Patterns Explained: Dependency Injections With Code Examples

Dependency inversion principle Dependency Software design Spring Framework Java (programming language)

Published at DZone with permission of Ranga Karanam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Application Architecture Design Principles
  • Is Podman a Drop-in Replacement for Docker?
  • Explainable AI: Making the Black Box Transparent
  • Incident Response Guide

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: