SlideShare uma empresa Scribd logo
1 de 13
Baixar para ler offline
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

Mais conteúdo relacionado

Destaque

11프로그래밍 김영일
11프로그래밍 김영일11프로그래밍 김영일
11프로그래밍 김영일
bit_blue
 
4 q09 presentation
4 q09 presentation4 q09 presentation
4 q09 presentation
Equatorial
 
Vocabulary describing people
Vocabulary describing peopleVocabulary describing people
Vocabulary describing people
jolehidy6
 
System Furniture Design
System Furniture DesignSystem Furniture Design
System Furniture Design
lbridge89
 
The Only Way is Essex - Frail to Raging.
The Only Way is Essex - Frail to Raging.The Only Way is Essex - Frail to Raging.
The Only Way is Essex - Frail to Raging.
bellahoy
 
Görög nyár(4)+ani (nx power lite)
Görög nyár(4)+ani (nx power lite)Görög nyár(4)+ani (nx power lite)
Görög nyár(4)+ani (nx power lite)
VarganeAnny
 
耶穌的文字學
耶穌的文字學耶穌的文字學
耶穌的文字學
chengchunhao
 
Fotoalbum(2)+ani (nx power lite)
Fotoalbum(2)+ani (nx power lite)Fotoalbum(2)+ani (nx power lite)
Fotoalbum(2)+ani (nx power lite)
VarganeAnny
 

Destaque (20)

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

Semelhante a Brief introduction into dependencies

David Thiel - Secure Development On iOS
David Thiel - Secure Development On iOSDavid Thiel - Secure Development On iOS
David Thiel - Secure Development On iOS
Source Conference
 
Giving (and taking) back - Mike Fiedler
Giving (and taking) back - Mike FiedlerGiving (and taking) back - Mike Fiedler
Giving (and taking) back - Mike Fiedler
Devopsdays
 

Semelhante a Brief introduction into dependencies (20)

Desenvolvimento moderno de aplicativos android
Desenvolvimento moderno de aplicativos androidDesenvolvimento moderno de aplicativos android
Desenvolvimento moderno de aplicativos android
 
Feedback on Part 1 of the CSLP
Feedback on Part 1 of the CSLPFeedback on Part 1 of the CSLP
Feedback on Part 1 of the CSLP
 
10 Big Ideas from Industry
10 Big Ideas from Industry10 Big Ideas from Industry
10 Big Ideas from Industry
 
8 Principles for Enabling Build/Measure/Learn: Lean Engineering in Action
8 Principles for Enabling Build/Measure/Learn: Lean Engineering in Action8 Principles for Enabling Build/Measure/Learn: Lean Engineering in Action
8 Principles for Enabling Build/Measure/Learn: Lean Engineering in Action
 
Integreation
IntegreationIntegreation
Integreation
 
Java ide comparision
Java ide comparisionJava ide comparision
Java ide comparision
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 
6 Principles for Enabling Build/Measure/Learn: Lean Engineering in Action
6 Principles for Enabling Build/Measure/Learn: Lean Engineering in Action6 Principles for Enabling Build/Measure/Learn: Lean Engineering in Action
6 Principles for Enabling Build/Measure/Learn: Lean Engineering in Action
 
Tutorial test driven development with Visual Studio 2012
Tutorial test driven development with Visual Studio 2012Tutorial test driven development with Visual Studio 2012
Tutorial test driven development with Visual Studio 2012
 
Intellij idea features
Intellij idea featuresIntellij idea features
Intellij idea features
 
Fed Up Of Framework Hype Dcphp
Fed Up Of Framework Hype DcphpFed Up Of Framework Hype Dcphp
Fed Up Of Framework Hype Dcphp
 
David Thiel - Secure Development On iOS
David Thiel - Secure Development On iOSDavid Thiel - Secure Development On iOS
David Thiel - Secure Development On iOS
 
Intelli j idea-report
Intelli j idea-reportIntelli j idea-report
Intelli j idea-report
 
ISS Art. How to do IT. Kotlin Multiplatform
ISS Art. How to do IT. Kotlin MultiplatformISS Art. How to do IT. Kotlin Multiplatform
ISS Art. How to do IT. Kotlin Multiplatform
 
Lean engineering for lean/balanced teams: lessons learned (and still learning...
Lean engineering for lean/balanced teams: lessons learned (and still learning...Lean engineering for lean/balanced teams: lessons learned (and still learning...
Lean engineering for lean/balanced teams: lessons learned (and still learning...
 
Android ndk: Entering the native world
Android ndk: Entering the native worldAndroid ndk: Entering the native world
Android ndk: Entering the native world
 
Sikuli
SikuliSikuli
Sikuli
 
Giving (and taking) back - Mike Fiedler
Giving (and taking) back - Mike FiedlerGiving (and taking) back - Mike Fiedler
Giving (and taking) back - Mike Fiedler
 
Tdd in android (mvp)
Tdd in android (mvp)Tdd in android (mvp)
Tdd in android (mvp)
 
Enabling Lean at Enterprise Scale: Lean Engineering in Action
Enabling Lean at Enterprise Scale: Lean Engineering in ActionEnabling Lean at Enterprise Scale: Lean Engineering in Action
Enabling Lean at Enterprise Scale: Lean Engineering in Action
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

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