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
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. How I Explained Dependency Injection to My Team

How I Explained Dependency Injection to My Team

Siva Prasad Reddy Katamreddy user avatar by
Siva Prasad Reddy Katamreddy
·
Jun. 19, 12 · Interview
Like (2)
Save
Tweet
Share
20.22K Views

Join the DZone community and get the full member experience.

Join For Free
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 
{
	//This method validates the given address and return longitude/latitude details.	
	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 : http://www.sivalabs.in/2012/06/how-i-explained-dependency-injection-to.html
 
 
 
Dependency injection unit test teams Web Service Service provider

Published at DZone with permission of Siva Prasad Reddy Katamreddy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Spring Cloud
  • Journey to Event Driven, Part 1: Why Event-First Programming Changes Everything
  • What Is API-First?
  • What Is JavaScript Slice? Practical Examples and 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
  • +1 (919) 678-0300

Let's be friends: