SlideShare a Scribd company logo
Dependencies with
and without Guice
Outline

    What are dependencies?
    How dependencies cause problems
    Inversion of Control and Hollywood
    Guice – the solution for everything (almost)
            Providers
            The creation of a new object




15.04.2011                       Joel Krebs         2
What are dependencies?
- or why not to code only one class

    Classes depends on others, that comes with
     Object orienteted programming (OOP)
    Dependencies are classes, that are used by
     other classes in order to work
    Example:             Board




                   Die                Player




15.04.2011               Joel Krebs               3
Why are dependencies bad?
- well that depends...

    What are key features of 'good code'?
            Testable
            Modular
            Changable
            …
    Imagine that for huge applications...




15.04.2011                Joel Krebs         4
Inversion of Control
- what has Hollywood to do with all this?

    Inversion of Control (IoF) is a design pattern to
     reduce dependencies without any frameworks
    Difference to procedural architecture:
             Board              Die                Player




                      Die

                                           Board

                     Player

15.04.2011                    Joel Krebs                    5
Methods for Inversion of Control
- something everybody can do

    General rules:
            Use interfaces
            Use getters and setters
    1. Using factories
             IDie die = DieFactory.get()
    2. Using constructors injection
             public Board(IPlayer player, IDie die)
    3. Using setter injection
             public void setDie(IDie die)
15.04.2011                       Joel Krebs           6
Guice
- well, it works for Google, let's try

    Real dependency injection only works with
     frameworks (e.g. Guice, Spring)
    They can save you a lot of time and coding, but
     not for too small applications
    Guice needs you...
            ...to tell Guice wich Interface maps to which class
             => module
            ...to give him the necesarry information how to
             construct a object => Provider

15.04.2011                        Joel Krebs                       7
The Provider
- let's just copy & paste

import com.google.inject.Inject;
import com.google.inject.Provider;

public class GameProvider implements Provider<Game> {
  private Provider<IDie> dieProvider ;

    @Inject
    public GameProvider(Provider<IDie> dieProvider) {
      this.dieProvider = dieProvider;
    }

    @Override
    public Game get() {
      Player[] players = { new Player("Jack"), new Player("Jill")};
      Game game = new Game(12, players, dieProvider .get());

        game.setSquareToLadder(2, 4);
        game.setSquareToLadder(7, 2);
        game.setSquareToSnake(11, -6);
        game.setSquareToLargeSquare(4);
        game.setSquareToTrapDoor(10, -6);

        return game;
    }
}
15.04.2011                                  Joel Krebs                8
The Module
- different modules for testing and use
package snakes;

import com.google.inject.AbstractModule;

public class SnakesModule extends AbstractModule {
  @Override
  protected void configure() {
     bind(IDie.class)
      .to(Die.class);

        bind(Game.class)
         .toProvider(GameProvider.class);
    }
}


public class SnakesTestModule extends AbstractModule {
  @Override
  protected void configure() {
     bind(IDie.class)
      .toInstance(context.mock(IDie.class));

        bind(Game.class)
         .toProvider(GameProvider.class);
    }
}
15.04.2011                                  Joel Krebs   9
How we get new objects
- all roads lead to Rome...or a game

    So if I want a board game, what happens?
                          Main method
              Injector.getInstance(Game.class)




                         SnakesModule
              bind(Game.class)
               .toProvider(GameProvider.class)




                         GameProvider
              new Game(... dieProvider.get())


15.04.2011                  Joel Krebs           10
Improvements
- there's always a way to code better

    Use annotions that are provided by Guice
            @named
            @singelton
    Merge modules
    Merge providers




15.04.2011                Joel Krebs            11
Conclusions
- doesn't make it all more complicate?

    Reduce dependencies in general improves your
     code in many ways
    It needs a certain kind of mindset, but you get
     used to it
    Frameworks like Guice can improve your code
     as well and may save you a lot of time
            But I would not use them for too small projects



15.04.2011                        Joel Krebs                   12
Questions
- experiences, smart remarks, suggestions




                           Joel Krebs
                           joel.krebs@students.unibe.ch
                           @jomikr on
                           www.aleaiactaest.ch

15.04.2011         Joel Krebs                             13

More Related Content

PDF
KevlinHenney_PuttingThereIntoArchitecture
PPT
3.o o design -_____________lecture 3
PPTX
2010 programming contest preliminary feedback
PDF
Introduction to Object Oriented Design
PPTX
Dependency injection
PPT
Nichodemus rudaheranwa2
PPS
Csodás világ(3)+ani (nx powerlite)
PPS
Yemeni pillanatok+ani (nx power lite)
KevlinHenney_PuttingThereIntoArchitecture
3.o o design -_____________lecture 3
2010 programming contest preliminary feedback
Introduction to Object Oriented Design
Dependency injection
Nichodemus rudaheranwa2
Csodás világ(3)+ani (nx powerlite)
Yemeni pillanatok+ani (nx power lite)

Viewers also liked (20)

PDF
Best Work
PPTX
11프로그래밍 김영일
PDF
4 q09 presentation
PDF
Vocabulary describing people
ODP
Svd7 ts hich2
PPSX
Технологические основы для построения облачной среды
PDF
Mathematics Olympiad 2
PPTX
2nd mini project instructions
PDF
Il secondo numero del nostro giornalino-Marzo 2016
PPTX
System Furniture Design
PPTX
Mijn derde portret in oliever van Koningin Maxima Saskia Vugts Portretschilder
PPTX
The Only Way is Essex - Frail to Raging.
PPS
Görög nyár(4)+ani (nx power lite)
DOCX
Workshop 2015 recuperaciones grado 8 vo
PPTX
Saludable profile
PDF
Physical constants
PPS
耶穌的文字學
PDF
発達の心配なお子さんのためのiPad活用講座
PDF
Projekty na lekcji języka obcego.
PPS
Fotoalbum(2)+ani (nx power lite)
Best Work
11프로그래밍 김영일
4 q09 presentation
Vocabulary describing people
Svd7 ts hich2
Технологические основы для построения облачной среды
Mathematics Olympiad 2
2nd mini project instructions
Il secondo numero del nostro giornalino-Marzo 2016
System Furniture Design
Mijn derde portret in oliever van Koningin Maxima Saskia Vugts Portretschilder
The Only Way is Essex - Frail to Raging.
Görög nyár(4)+ani (nx power lite)
Workshop 2015 recuperaciones grado 8 vo
Saludable profile
Physical constants
耶穌的文字學
発達の心配なお子さんのためのiPad活用講座
Projekty na lekcji języka obcego.
Fotoalbum(2)+ani (nx power lite)
Ad

Similar to Brief introduction into dependencies (20)

PDF
Java onguice20070426
PPTX
Dependency injection using Google guice
PDF
Guice - dependency injection framework
PDF
Guice
PDF
sfdsdfsdfsdf
PDF
PDF
Mock Objects, Design and Dependency Inversion Principle
PPT
Google Guice
PDF
PDF
PPTX
Introduction to Google Guice
PDF
L07 Frameworks
PPTX
Dependency Inversion Principle
PPTX
Eway google-guice presentation
PDF
Jug Guice Presentation
PDF
Devoxx 2012 (v2)
PPTX
L09 Frameworks
PPTX
Design for testability as a way to good coding (SOLID and IoC)
ODP
Introduction to Spring Framework and Spring IoC
PPTX
A brief overview of java frameworks
Java onguice20070426
Dependency injection using Google guice
Guice - dependency injection framework
Guice
sfdsdfsdfsdf
Mock Objects, Design and Dependency Inversion Principle
Google Guice
Introduction to Google Guice
L07 Frameworks
Dependency Inversion Principle
Eway google-guice presentation
Jug Guice Presentation
Devoxx 2012 (v2)
L09 Frameworks
Design for testability as a way to good coding (SOLID and IoC)
Introduction to Spring Framework and Spring IoC
A brief overview of java frameworks
Ad

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Spectroscopy.pptx food analysis technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
cuic standard and advanced reporting.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
KodekX | Application Modernization Development
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
sap open course for s4hana steps from ECC to s4
Diabetes mellitus diagnosis method based random forest with bat algorithm
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Spectroscopy.pptx food analysis technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
Reach Out and Touch Someone: Haptics and Empathic Computing
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
cuic standard and advanced reporting.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Review of recent advances in non-invasive hemoglobin estimation
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Spectral efficient network and resource selection model in 5G networks
KodekX | Application Modernization Development
Per capita expenditure prediction using model stacking based on satellite ima...
Digital-Transformation-Roadmap-for-Companies.pptx
Unlocking AI with Model Context Protocol (MCP)
sap open course for s4hana steps from ECC to s4

Brief introduction into dependencies

  • 2. Outline  What are dependencies?  How dependencies cause problems  Inversion of Control and Hollywood  Guice – the solution for everything (almost)  Providers  The creation of a new object 15.04.2011 Joel Krebs 2
  • 3. What are dependencies? - or why not to code only one class  Classes depends on others, that comes with Object orienteted programming (OOP)  Dependencies are classes, that are used by other classes in order to work  Example: Board Die Player 15.04.2011 Joel Krebs 3
  • 4. Why are dependencies bad? - well that depends...  What are key features of 'good code'?  Testable  Modular  Changable  …  Imagine that for huge applications... 15.04.2011 Joel Krebs 4
  • 5. Inversion of Control - what has Hollywood to do with all this?  Inversion of Control (IoF) is a design pattern to reduce dependencies without any frameworks  Difference to procedural architecture: Board Die Player Die Board Player 15.04.2011 Joel Krebs 5
  • 6. Methods for Inversion of Control - something everybody can do  General rules:  Use interfaces  Use getters and setters  1. Using factories IDie die = DieFactory.get()  2. Using constructors injection public Board(IPlayer player, IDie die)  3. Using setter injection public void setDie(IDie die) 15.04.2011 Joel Krebs 6
  • 7. Guice - well, it works for Google, let's try  Real dependency injection only works with frameworks (e.g. Guice, Spring)  They can save you a lot of time and coding, but not for too small applications  Guice needs you...  ...to tell Guice wich Interface maps to which class => module  ...to give him the necesarry information how to construct a object => Provider 15.04.2011 Joel Krebs 7
  • 8. The Provider - let's just copy & paste import com.google.inject.Inject; import com.google.inject.Provider; public class GameProvider implements Provider<Game> { private Provider<IDie> dieProvider ; @Inject public GameProvider(Provider<IDie> dieProvider) { this.dieProvider = dieProvider; } @Override public Game get() { Player[] players = { new Player("Jack"), new Player("Jill")}; Game game = new Game(12, players, dieProvider .get()); game.setSquareToLadder(2, 4); game.setSquareToLadder(7, 2); game.setSquareToSnake(11, -6); game.setSquareToLargeSquare(4); game.setSquareToTrapDoor(10, -6); return game; } } 15.04.2011 Joel Krebs 8
  • 9. The Module - different modules for testing and use package snakes; import com.google.inject.AbstractModule; public class SnakesModule extends AbstractModule { @Override protected void configure() { bind(IDie.class) .to(Die.class); bind(Game.class) .toProvider(GameProvider.class); } } public class SnakesTestModule extends AbstractModule { @Override protected void configure() { bind(IDie.class) .toInstance(context.mock(IDie.class)); bind(Game.class) .toProvider(GameProvider.class); } } 15.04.2011 Joel Krebs 9
  • 10. How we get new objects - all roads lead to Rome...or a game  So if I want a board game, what happens? Main method Injector.getInstance(Game.class) SnakesModule bind(Game.class)  .toProvider(GameProvider.class) GameProvider new Game(... dieProvider.get()) 15.04.2011 Joel Krebs 10
  • 11. Improvements - there's always a way to code better  Use annotions that are provided by Guice  @named  @singelton  Merge modules  Merge providers 15.04.2011 Joel Krebs 11
  • 12. Conclusions - doesn't make it all more complicate?  Reduce dependencies in general improves your code in many ways  It needs a certain kind of mindset, but you get used to it  Frameworks like Guice can improve your code as well and may save you a lot of time  But I would not use them for too small projects 15.04.2011 Joel Krebs 12
  • 13. Questions - experiences, smart remarks, suggestions Joel Krebs joel.krebs@students.unibe.ch @jomikr on www.aleaiactaest.ch 15.04.2011 Joel Krebs 13