About Siva Reddy

Katamreddy Siva Prasad is a Senior Software Engineer working in E-Commerce domain. His areas of interest include Object Oriented Design, SOLID Design principles, RESTful WebServices and OpenSource softwares including Spring, MyBatis and Jenkins.

How I explained Dependency Injection to My Team

Recently our company started developing a new java based web application and after some evaluation process we decided to use Spring.
But many of the team members are not aware of Spring and Dependency Injection principles. So I was asked to give a crash course on what is Dependency Injection and basics on Spring.

Instead of telling all the theory about IOC/DI I thought of explaining with an example.

Requirement: We will get some Customer Address and we need to validate the address.
After some evaluation we thought of using Google Address Validation Service.

Legacy(Bad) Approach:

Just create an AddressVerificationService class and implement the logic.

Assume GoogleAddressVerificationService is a service provided by Google which takes Address as a String and Return longitude/latitude.

class AddressVerificationService 
{
   public String validateAddress(String address)
 {
 GoogleAddressVerificationService gavs = new GoogleAddressVerificationService();
  String result = gavs.validateAddress(address);  
  return result;
 }
}

Issues with this approach: 

1. If you want to change your Address Verification Service Provider you need to change the logic.
2. You can’t Unit Test with some Dummy AddressVerificationService (Using Mock Objects)

Due to some reason Client ask us to support multiple AddressVerificationService Providers and we need to determine which service to use at runtime.

To accomidate this you may thought of changing the above class as below:

class AddressVerificationService
{
//This method validates the given address and return longitude/latitude details.
 public String validateAddress(String address)
 {
  String result = null;
  int serviceCode = 2; // read this code value from a config file
  if(serviceCode == 1)
  {
   GoogleAddressVerificationService googleAVS = new GoogleAddressVerificationService();
   result = googleAVS.validateAddress(address);
  } else if(serviceCode == 2)
  {
   YahooAddressVerificationService yahooAVS = new YahooAddressVerificationService();
   result = yahooAVS.validateAddress(address);
  }
  return result;
 }
}

Issues with this approach: 
 
1. Whenever you need to support a new Service Provider you need to add/change logic using if-else-if.
2. You can’t Unit Test with some Dummy AddressVerificationService (Using Mock Objects)

IOC/DI Approach:

In the above approaches AddressVerificationService is taking the control of creating its dependencies.
So whenever there is a change in its dependencies the AddressVerificationService will change.

Now let us rewrite the AddressVerificationService using IOC/DI pattern.

 class AddressVerificationService
 {
  private AddressVerificationServiceProvider serviceProvider;
  
  public AddressVerificationService(AddressVerificationServiceProvider serviceProvider) {
   this.serviceProvider = serviceProvider;
  }
  
  public String validateAddress(String address)
  {
   return this.serviceProvider.validateAddress(address);
  }
 }
 
 interface AddressVerificationServiceProvider
 {
  public String validateAddress(String address);
 }

Here we are injecting the AddressVerificationService dependency AddressVerificationServiceProvider.

Now let us implement the AddressVerificationServiceProvider with multiple provider services.

 class YahooAVS implements AddressVerificationServiceProvider
 {
  @Override
  public String validateAddress(String address) {
   System.out.println("Verifying address using YAHOO AddressVerificationService");
   return yahooAVSAPI.validate(address);
  }  
 }

 class GoogleAVS implements AddressVerificationServiceProvider
 {
  @Override
  public String validateAddress(String address) {
   System.out.println("Verifying address using Google AddressVerificationService");
   return googleAVSAPI.validate(address);
  }
 }

Now the Client can choose which Service Provider’s service to use as follows:

 AddressVerificationService verificationService = null;
 AddressVerificationServiceProvider provider = null;
 provider = new YahooAVS();//to use YAHOO AVS
 provider = new GoogleAVS();//to use Google AVS
 
 verificationService = new AddressVerificationService(provider);
 String lnl = verificationService.validateAddress("HitechCity, Hyderabad");
 System.out.println(lnl);

For Unit Testing we can implement a Mock AddressVerificationServiceProvider.

 class MockAVS implements AddressVerificationServiceProvider
 {
  @Override
  public String validateAddress(String address) {
   System.out.println("Verifying address using MOCK AddressVerificationService");
   return "<response><longitude>123</longitude><latitude>4567</latitude>";
  }
 }
 
 AddressVerificationServiceProvider provider = null;
 provider = new MockAVS();//to use MOCK AVS  
 AddressVerificationServiceIOC verificationService = new AddressVerificationServiceIOC(provider);
 String lnl = verificationService.validateAddress("Somajiguda, Hyderabad");
 System.out.println(lnl);

With this approach we elemenated the issues with above Non-IOC/DI based approaches.
1. We can provide support for as many Provides as we wish. Just implement AddressVerificationServiceProvider and inject it.
2. We can unit test using Dummy Data using Mock Implementation.

So by following Dependency Injection principle we can create interface-based loosely-coupled and easily testable services.

Reference: How I explained Dependency Injection to My Team from our JCG partner Siva Reddy at the My Experiments on Technology blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "How I explained Dependency Injection to My Team"

  1. Birender Singh says:

    Thanks for sharing.

Leave a Reply


− 2 = seven



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.