An Introduction to Dependency Inversion Principle

Post on 10-May-2015

1.431 views 2 download

Tags:

description

Introduces what is Inversion of Control, Dependency Injection and How they relates to the Dependency Inversion Principle

Transcript of An Introduction to Dependency Inversion Principle

Dependency Inversion PrincipleBy Dunith Dhanushka

Agenda

• Walkthrough of a real world scenario.• What is Inversion of Control?• What is Dependency Injection?• Multiple forms of Dependency Injection• IoC Containers

R.I.P Steve Jobs (1955 -2011)!

SOLID Principles

• Single Responsibility Principle• Open Closed Principle• Lizkov’s Substitution Principle• Interface Segregation Principle

• Dependency Inversion Principle

Meet Joe the developer!!

Joe’s contract is to build a IMDB clone!

First cut of the Movie Lister app

Problems with it

• Can’t extend the application without modifying the existing code.

• Violates Open/Closed principle!!! :S

Introduction of Interfaces

New Movie Lister App

Issues of new Movie Lister

• MovieLister class has to talk to both interface and implementation!!

• This makes MovieLister less portable.• This makes MovieLister less reusable.• Switching implementations requires a code

change! :@• Hard to unit test.

How can we fix this???

Its IT! We got remedy! ;)

• Using Setters ( Use a setter to set a Finder instance for MovieLister)

• Passing a Finder instance as constructor argument for MovieLister

• Use a Factory of Finders for MovieLister • Use a ServiceLocator

Using a setter

What really happened there?

• MovieLister depends on the Finder• Previously, MovieLister took the control of

initiating it’s dependency.• But in new version, dependency has been

instantiated by some other party for the MovieLister.

• This is called “Inversion of Control” (IoC)

This makes MovieLister

• Share across other developers.• Makes portable.• Encourages unit testing.• Preserves OCP (Movie Lister doesn’t know any

thing about its crappy implementers. Also plugging a new Finder doesn’t require a code change)

• Enables the use of Mock Objects.

Ways to achieve IoC

• Dependency Injection• Dependency Inversion Principle– A. High-level modules should not depend on low-

level modules. Both should depend on abstractions.

– B. Abstractions should not depend upon details. Details should depend upon abstractions.

• Coined by Martin Fowler

Methods of DI

• Constructor Injection• Setter Injection• Interface Injection

IoC Containers

• How does an IoC container works?

Popular IoC containers for Java

• Pico Container• Spring• JBoss Micro kernel• Google Guice• OSGi ( sort of DI, but very advanced)

Joe managed to save his head!

• Joe used Spring container.• He implemented the MovieLister as a Spring

bean.• In the beans.xml file, he wired the specific

Finder implementation to it’s interface!• Voila!

Thank you!

• We’ll meet in the next week with more Spring examples!

• Adios!