SlideShare une entreprise Scribd logo
1  sur  32
Inversion of Control
         Guy Nir
      January 2012
Agenda

»   The problem …
»   Inversion of Control
»   Benefits
»   Acceptance misbelieves
The problem …
The problem …
public class MediaPlayer {

     private InputSource inputSource;
     private OutputDevice outputDevice;

     /**
      * Class constructor.
      */
     public MediaPlayer() {
         inputSource = new FileInputSource(“c:/media/movie.avi”);
         outputDevice = new Screen();
     }

     /**
      * Play media.
      */
     public void play() {
         while (running) {
              // Read from 'inputSource' and write to 'outputDevice'.
         }
     }
}
The problem …
/**
 * Represents an input source.
 */
public interface InputSource {

     // Business methods.

}


/**
 * Represents an output device.
 */
public interface OutputDevice {

     // Business methods.

}
The problem …




               Media Player




  << InputSource >>     <<TargetDevice>>
     File (C:/….)            Screen
The problem …

                                       Configuration file
                                     source =
                                     C:/media/file.avi


               Media Player




  << InputSource >>     <<TargetDevice>>
      File (<?>)             Screen
The problem …

                                       Configuration file
                                     source =
                                     C:/media/file.avi

                                     targetClass =
                                     example.ScreenTarget
               Media Player




  << InputSource >>     <<TargetDevice>>
      File (<?>)              <?>
The problem …

                                        Configuration file




Database
                Media Player
                               X
                                            X
                                      source =
                                      C:/media/file.avi

                                      targetClass =
                                      example.ScreenTarget




   << InputSource >>     <<TargetDevice>>
       File (<?>)              <?>
The problem …

             Web service                  Configuration file




Database
                Media Player
                               X
                                              X
                                        source =
                                        C:/media/file.avi

                                        targetClass =
                                        example.ScreenTarget




   << InputSource >>       <<TargetDevice>>
       File (<?>)                <?>
The problem …

             Web service                  Configuration file




Database
                Media Player
                               X
                                           X
                                      source =
                                      C:/media/file.avi

                                      targetClass =
                                      example.ScreenTarget




   << InputSource >>       << Target >>
       File (<?>)              <?>
The problem …

The problem with the design …
Driven by behavior and not by functionality
»   Too strict, cannot be changed easily.
»   Hard to extend
»   Can barely be reused (if at all).
                                            [1]
»   Contradicts the ‘Open-Close principle’.




[1] Open/closed principle by Bertrand Meyer
The problem …




                    Media Player



    << InputSource >>         << TargetDevice >>
       File (C:/….)                 Screen
The problem …



    << InputSource >>         << TargetDevice >>




                    Media Player
The problem …
/**
 * Represents an input source.
 */
public interface InputSource {

     // Business methods.

}


/**
 * Represents an output device.
 */
public interface OutputDevice {

     // Business methods.

}
The problem …
public class MediaPlayer {

     private InputSource inputSource;
     private OutputDevice outputDevice;

     /**
      * Class constructor.
      */
     public MediaPlayer() {
         inputSource = new FileInputSource(“c:/media/movie.avi”);
         outputDevice = new Screen();
     }

     /**
      * Play media.
      */
     public void play() {
         while (running) {
              // Read from 'inputSource' and write to 'outputDevice'.
         }
     }
}
The problem …
public class MediaPlayer {

     private InputSource inputSource;
     private OutputDevice outputDevice;

     public void setInputSource(InputSource inputSource) {
         this.inputSource = inputSource;
     }

     public void setOutputDevice(OutputDevice outputDevice) {
         this.outputDevice = outputDevice;
     }
                                                                 That’s our
     /**
      * Play media.
                                                              business logic.
      */
     public void play() {
         while (running) {
              // Read from 'inputSource' and write to 'outputDevice'.
         }
     }
}
The problem …

What we’ve accomplished…
Design by functionality
» Concentrates on functionality only
    No lookup or creation of resources,
    Separation of concerns.


» We’re not limited to certain behavior
    Source and Target can be anything,
    Source and Target can be fetched from any where
      • Configuration file, Database, Web service, …
The problem …

What we’ve accomplished… (continued)

» We can inject any source / target !
    E.g.: deployable on other platforms
    Quickly inject mockups
      • Required for Agile development
      • Required for unit testing.
Inversion of Control
Inversion of Control

» Is a conceptual abstraction in software development.
                                          [1]
» Introduced by Martin Fowler’s in 1988.
» Has 3 flavors,
      Constructor injection (Dependency injection)
      Setter injection (Dependency injection)
      Dependency lookup.




[1] Martin Fowler – Dependency injection
Inversion of Control

Constructor injection
» Inject required resources via constructor.

public class ConstructorInjection {

    private final DataSource dataSource;
    private final int timeout;

    /**
     * Class constructor.
     *
     * @param dataSource Database connection.
     * @param timeout     Query timeout.
     */
    public ConstructorInjection(DataSource dataSource, int timeout) { ... }
}
Inversion of Control

Constructor injection
» Pros:
     Require user to specify all required resources.
     Object is guaranteed to be injected with resources.
       • May cancel object if a resource is not fulfilled ( == null).


public ConstructorInjection(DataSource dataSource, int timeout) {
    if (dataSource == null || timeout < 1)
         throw new IllegalArgumentException();

    this.dataSource = dataSource;
    this.timeout = timeout;
}
Inversion of Control

Constructor injection
» Cons:
     Sometimes tedious,
       • Must inject all resources or replace them with null.
     Does not work well for a large number of dependencies.


public BadConstructorInjection(DataSource dataSource,
         int timeout, Dialect dialect, String characterSet, double threashold,
         boolean eagerly, Formatter messageFormatter, ...) {
}
Inversion of Control

Setter injection
» Inject required resources via setXXX() method.
     Using JavaBean™ mutators.
public class SetterInjection {

    private DataSource dataSource;
    private int timeout;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
}
Inversion of Control

Setter injection
» Pros:
     Inject as many dependencies as you want.
     Each resource/value treated independently.
» Cons:
     Debatable issues …
public void setTimeout(int timeout) {
    if (timeout < 0) {
         throw new IllegalArgumentException("Timeout cannot be negative.");
    }

    this.timeout = timeout;
}
Inversion of Control

Dependency lookup
» Split resource locating between user and
  implementation.
» Used much less than Constructor/Setter injections.

public void lookupDS(JNDIContext context) throws NamingException {
    dataSource = (DataSource) context.lookup("env:/ds/oracleDataSource");
}

public void locateConfigFile(File rootDir) throws NamingException {
    // Search file system for configuration file, starting with ‘rootDir’.
}
Benefits
Benefits

» Full separation of concerns
    Reusable components
    Extendable components.
» Design and development by functionality.
    Each object/module is focused on its business logic.
    Produce a better, small, more efficient code.
» Agility.
    Excellent for Agile practices (e.g.: XP, TDD, …).
Acceptance misbelieves
Open discussion about Inversion of Control
Acceptance misbelieves

» Psychologically, hard to accept a new working
  methodology.

» Tendency to think that IoC creates too much code.

» It looks complex.
Q&A

Contenu connexe

Similaire à IoC-Inversion of Control Explained

KOIN for dependency Injection
KOIN for dependency InjectionKOIN for dependency Injection
KOIN for dependency InjectionKirill Rozov
 
A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesDavid Wengier
 
Deep dive in Citrix Troubleshooting
Deep dive in Citrix TroubleshootingDeep dive in Citrix Troubleshooting
Deep dive in Citrix TroubleshootingDenis Gundarev
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis Hassler
 
Mini musicplayer C# personal project
Mini musicplayer C# personal projectMini musicplayer C# personal project
Mini musicplayer C# personal projectChen Chen
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android JetpackAhmad Arif Faizin
 
BizTalk Application Deployment
BizTalk Application DeploymentBizTalk Application Deployment
BizTalk Application DeploymentDaniel Toomey
 
Advanced Windows Debugging
Advanced Windows DebuggingAdvanced Windows Debugging
Advanced Windows DebuggingBala Subra
 
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek PiotrowskiJDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek PiotrowskiPROIDEA
 
Decomposing the Monolith using modern-day .NET and a touch of microservices
Decomposing the Monolith using modern-day .NET and a touch of microservicesDecomposing the Monolith using modern-day .NET and a touch of microservices
Decomposing the Monolith using modern-day .NET and a touch of microservicesDennis Doomen
 
Apache ant
Apache antApache ant
Apache antkoniik
 
Ad103 - Have it Your Way: Extending IBM Lotus Domino Designer
Ad103 - Have it Your Way: Extending IBM Lotus Domino DesignerAd103 - Have it Your Way: Extending IBM Lotus Domino Designer
Ad103 - Have it Your Way: Extending IBM Lotus Domino Designerddrschiw
 
Introduction to directshow II
Introduction to directshow IIIntroduction to directshow II
Introduction to directshow IIYoss Cohen
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slideshelenmga
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin componentsPeter Lehto
 
Android installation guide
Android installation guideAndroid installation guide
Android installation guidemagicshui
 

Similaire à IoC-Inversion of Control Explained (20)

KOIN for dependency Injection
KOIN for dependency InjectionKOIN for dependency Injection
KOIN for dependency Injection
 
A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project Files
 
Deep dive in Citrix Troubleshooting
Deep dive in Citrix TroubleshootingDeep dive in Citrix Troubleshooting
Deep dive in Citrix Troubleshooting
 
myslide1
myslide1myslide1
myslide1
 
myslide6
myslide6myslide6
myslide6
 
NewSeriesSlideShare
NewSeriesSlideShareNewSeriesSlideShare
NewSeriesSlideShare
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
Unity 5 Overview
Unity 5 OverviewUnity 5 Overview
Unity 5 Overview
 
Mini musicplayer C# personal project
Mini musicplayer C# personal projectMini musicplayer C# personal project
Mini musicplayer C# personal project
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
 
BizTalk Application Deployment
BizTalk Application DeploymentBizTalk Application Deployment
BizTalk Application Deployment
 
Advanced Windows Debugging
Advanced Windows DebuggingAdvanced Windows Debugging
Advanced Windows Debugging
 
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek PiotrowskiJDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
JDD2015: ClassIndex - szybka alternatywa dla skanowania klas - Sławek Piotrowski
 
Decomposing the Monolith using modern-day .NET and a touch of microservices
Decomposing the Monolith using modern-day .NET and a touch of microservicesDecomposing the Monolith using modern-day .NET and a touch of microservices
Decomposing the Monolith using modern-day .NET and a touch of microservices
 
Apache ant
Apache antApache ant
Apache ant
 
Ad103 - Have it Your Way: Extending IBM Lotus Domino Designer
Ad103 - Have it Your Way: Extending IBM Lotus Domino DesignerAd103 - Have it Your Way: Extending IBM Lotus Domino Designer
Ad103 - Have it Your Way: Extending IBM Lotus Domino Designer
 
Introduction to directshow II
Introduction to directshow IIIntroduction to directshow II
Introduction to directshow II
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin components
 
Android installation guide
Android installation guideAndroid installation guide
Android installation guide
 

Dernier

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Exploring ChatGPT Prompt Hacks To Maximally Optimise Your Queries
Exploring ChatGPT Prompt Hacks To Maximally Optimise Your QueriesExploring ChatGPT Prompt Hacks To Maximally Optimise Your Queries
Exploring ChatGPT Prompt Hacks To Maximally Optimise Your QueriesSanjay Willie
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 

Dernier (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Exploring ChatGPT Prompt Hacks To Maximally Optimise Your Queries
Exploring ChatGPT Prompt Hacks To Maximally Optimise Your QueriesExploring ChatGPT Prompt Hacks To Maximally Optimise Your Queries
Exploring ChatGPT Prompt Hacks To Maximally Optimise Your Queries
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 

IoC-Inversion of Control Explained

  • 1. Inversion of Control Guy Nir January 2012
  • 2. Agenda » The problem … » Inversion of Control » Benefits » Acceptance misbelieves
  • 4. The problem … public class MediaPlayer { private InputSource inputSource; private OutputDevice outputDevice; /** * Class constructor. */ public MediaPlayer() { inputSource = new FileInputSource(“c:/media/movie.avi”); outputDevice = new Screen(); } /** * Play media. */ public void play() { while (running) { // Read from 'inputSource' and write to 'outputDevice'. } } }
  • 5. The problem … /** * Represents an input source. */ public interface InputSource { // Business methods. } /** * Represents an output device. */ public interface OutputDevice { // Business methods. }
  • 6. The problem … Media Player << InputSource >> <<TargetDevice>> File (C:/….) Screen
  • 7. The problem … Configuration file source = C:/media/file.avi Media Player << InputSource >> <<TargetDevice>> File (<?>) Screen
  • 8. The problem … Configuration file source = C:/media/file.avi targetClass = example.ScreenTarget Media Player << InputSource >> <<TargetDevice>> File (<?>) <?>
  • 9. The problem … Configuration file Database Media Player X X source = C:/media/file.avi targetClass = example.ScreenTarget << InputSource >> <<TargetDevice>> File (<?>) <?>
  • 10. The problem … Web service Configuration file Database Media Player X X source = C:/media/file.avi targetClass = example.ScreenTarget << InputSource >> <<TargetDevice>> File (<?>) <?>
  • 11. The problem … Web service Configuration file Database Media Player X X source = C:/media/file.avi targetClass = example.ScreenTarget << InputSource >> << Target >> File (<?>) <?>
  • 12. The problem … The problem with the design … Driven by behavior and not by functionality » Too strict, cannot be changed easily. » Hard to extend » Can barely be reused (if at all). [1] » Contradicts the ‘Open-Close principle’. [1] Open/closed principle by Bertrand Meyer
  • 13. The problem … Media Player << InputSource >> << TargetDevice >> File (C:/….) Screen
  • 14. The problem … << InputSource >> << TargetDevice >> Media Player
  • 15. The problem … /** * Represents an input source. */ public interface InputSource { // Business methods. } /** * Represents an output device. */ public interface OutputDevice { // Business methods. }
  • 16. The problem … public class MediaPlayer { private InputSource inputSource; private OutputDevice outputDevice; /** * Class constructor. */ public MediaPlayer() { inputSource = new FileInputSource(“c:/media/movie.avi”); outputDevice = new Screen(); } /** * Play media. */ public void play() { while (running) { // Read from 'inputSource' and write to 'outputDevice'. } } }
  • 17. The problem … public class MediaPlayer { private InputSource inputSource; private OutputDevice outputDevice; public void setInputSource(InputSource inputSource) { this.inputSource = inputSource; } public void setOutputDevice(OutputDevice outputDevice) { this.outputDevice = outputDevice; } That’s our /** * Play media. business logic. */ public void play() { while (running) { // Read from 'inputSource' and write to 'outputDevice'. } } }
  • 18. The problem … What we’ve accomplished… Design by functionality » Concentrates on functionality only  No lookup or creation of resources,  Separation of concerns. » We’re not limited to certain behavior  Source and Target can be anything,  Source and Target can be fetched from any where • Configuration file, Database, Web service, …
  • 19. The problem … What we’ve accomplished… (continued) » We can inject any source / target !  E.g.: deployable on other platforms  Quickly inject mockups • Required for Agile development • Required for unit testing.
  • 21. Inversion of Control » Is a conceptual abstraction in software development. [1] » Introduced by Martin Fowler’s in 1988. » Has 3 flavors,  Constructor injection (Dependency injection)  Setter injection (Dependency injection)  Dependency lookup. [1] Martin Fowler – Dependency injection
  • 22. Inversion of Control Constructor injection » Inject required resources via constructor. public class ConstructorInjection { private final DataSource dataSource; private final int timeout; /** * Class constructor. * * @param dataSource Database connection. * @param timeout Query timeout. */ public ConstructorInjection(DataSource dataSource, int timeout) { ... } }
  • 23. Inversion of Control Constructor injection » Pros:  Require user to specify all required resources.  Object is guaranteed to be injected with resources. • May cancel object if a resource is not fulfilled ( == null). public ConstructorInjection(DataSource dataSource, int timeout) { if (dataSource == null || timeout < 1) throw new IllegalArgumentException(); this.dataSource = dataSource; this.timeout = timeout; }
  • 24. Inversion of Control Constructor injection » Cons:  Sometimes tedious, • Must inject all resources or replace them with null.  Does not work well for a large number of dependencies. public BadConstructorInjection(DataSource dataSource, int timeout, Dialect dialect, String characterSet, double threashold, boolean eagerly, Formatter messageFormatter, ...) { }
  • 25. Inversion of Control Setter injection » Inject required resources via setXXX() method.  Using JavaBean™ mutators. public class SetterInjection { private DataSource dataSource; private int timeout; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void setTimeout(int timeout) { this.timeout = timeout; } }
  • 26. Inversion of Control Setter injection » Pros:  Inject as many dependencies as you want.  Each resource/value treated independently. » Cons:  Debatable issues … public void setTimeout(int timeout) { if (timeout < 0) { throw new IllegalArgumentException("Timeout cannot be negative."); } this.timeout = timeout; }
  • 27. Inversion of Control Dependency lookup » Split resource locating between user and implementation. » Used much less than Constructor/Setter injections. public void lookupDS(JNDIContext context) throws NamingException { dataSource = (DataSource) context.lookup("env:/ds/oracleDataSource"); } public void locateConfigFile(File rootDir) throws NamingException { // Search file system for configuration file, starting with ‘rootDir’. }
  • 29. Benefits » Full separation of concerns  Reusable components  Extendable components. » Design and development by functionality.  Each object/module is focused on its business logic.  Produce a better, small, more efficient code. » Agility.  Excellent for Agile practices (e.g.: XP, TDD, …).
  • 30. Acceptance misbelieves Open discussion about Inversion of Control
  • 31. Acceptance misbelieves » Psychologically, hard to accept a new working methodology. » Tendency to think that IoC creates too much code. » It looks complex.
  • 32. Q&A