inversion of control

32
Inversion of Control Guy Nir January 2012

Upload: guy-nir

Post on 10-May-2015

488 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Inversion of control

Inversion of ControlGuy Nir

January 2012

Page 2: Inversion of control

2

» The problem …» Inversion of Control» Benefits» Acceptance misbelieves

Agenda

Page 3: Inversion of control

The problem …

Page 4: Inversion of control

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

}}

}

Page 5: Inversion of control

5

The problem …

/** * Represents an input source. */public interface InputSource {

// Business methods.

}

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

// Business methods.

}

Page 6: Inversion of control

6

The problem …

<< InputSource

>>File (C:/….)

<<TargetDevice>>

Screen

Media Player

Page 7: Inversion of control

7

The problem …

<< InputSource

>>File (<?>)

<<TargetDevice>>

Screen

Configuration file

source = C:/media/file.avi

Media Player

Page 8: Inversion of control

8

The problem …

<< InputSource

>>File (<?>)

<<TargetDevice>><?>

Configuration file

source = C:/media/file.avi

targetClass =example.ScreenTarget

Media Player

Page 9: Inversion of control

9

The problem …

<< InputSource

>>File (<?>)

<<TargetDevice>><?>

Configuration file

source = C:/media/file.avi

targetClass =example.ScreenTarget

Media Player XXDatabase

Page 10: Inversion of control

10

The problem …

<< InputSource

>>File (<?>)

<<TargetDevice>><?>

Configuration file

source = C:/media/file.avi

targetClass =example.ScreenTarget

Media Player XXDatabase

Web service

Page 11: Inversion of control

11

The problem …

<< InputSource

>>File (<?>)

<< Target >><?>

Configuration file

source = C:/media/file.avi

targetClass =example.ScreenTarget

Media Player XXDatabase

Web service

Page 12: Inversion of control

12

» Too strict, cannot be changed easily.» Hard to extend» Can barely be reused (if at all).» Contradicts the ‘Open-Close principle’.[1]

The problem with the design …Driven by behavior and not by functionality

The problem …

[1] Open/closed principle by Bertrand Meyer

Page 13: Inversion of control

13

The problem …

<< InputSource

>>File (C:/….)

<< TargetDevice

>>Screen

Media Player

Page 14: Inversion of control

14

The problem …

<< InputSource

>>

<< TargetDevice

>>

Media Player

Page 15: Inversion of control

15

The problem …

/** * Represents an input source. */public interface InputSource {

// Business methods.

}

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

// Business methods.

}

Page 16: Inversion of control

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

}}

}

Page 17: Inversion of control

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;

}

/** * Play media. */public void play() {

while (running) {// Read from 'inputSource' and write to 'outputDevice'.

}}}

That’s our business logic.

Page 18: Inversion of control

18

» 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, …

What we’ve accomplished…Design by functionality

The problem …

Page 19: Inversion of control

19

» We can inject any source / target ! E.g.: deployable on other platforms Quickly inject mockups

• Required for Agile development• Required for unit testing.

What we’ve accomplished… (continued)

The problem …

Page 20: Inversion of control

Inversion of Control

Page 21: Inversion of control

21

» Is a conceptual abstraction in software development.» Introduced by Martin Fowler’s in 1988.[1]

» Has 3 flavors, Constructor injection (Dependency injection) Setter injection (Dependency injection) Dependency lookup.

Inversion of Control

[1] Martin Fowler – Dependency injection

Page 22: Inversion of control

22

» Inject required resources via constructor.

Constructor injection

Inversion of Control

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) { ... }

}

Page 23: Inversion of control

23

» 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).

Constructor injection

Inversion of Control

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

throw new IllegalArgumentException();

this.dataSource = dataSource;this.timeout = timeout;

}

Page 24: Inversion of control

24

» Cons: Sometimes tedious,

• Must inject all resources or replace them with null. Does not work well for a large number of dependencies.

Constructor injection

Inversion of Control

public BadConstructorInjection(DataSource dataSource,int timeout, Dialect dialect, String characterSet, double

threashold,boolean eagerly, Formatter messageFormatter, ...) {

}

Page 25: Inversion of control

25

» Inject required resources via setXXX() method. Using JavaBean™ mutators.

Setter injection

Inversion of Control

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;

}}

Page 26: Inversion of control

26

» Pros: Inject as many dependencies as you want. Each resource/value treated independently.

» Cons: Debatable issues …

Setter injection

Inversion of Control

public void setTimeout(int timeout) {if (timeout < 0) {

throw new IllegalArgumentException("Timeout cannot be negative.");}

this.timeout = timeout;}

Page 27: Inversion of control

27

» Split resource locating between user and implementation.

» Used much less than Constructor/Setter injections.

Dependency lookup

Inversion of Control

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

}

Page 28: Inversion of control

Benefits

Page 29: Inversion of control

29

» 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, …).

Benefits

Page 30: Inversion of control

Acceptance misbelievesOpen discussion about Inversion of Control

Page 31: Inversion of control

31

» Psychologically, hard to accept a new working methodology.

» Tendency to think that IoC creates too much code.

» It looks complex.

Acceptance misbelieves

Page 32: Inversion of control

Q & A