SlideShare a Scribd company logo
Dependency Injection
       with
    RoboGuice



   ©2013 Tom Braun <tom.braun@apps4use.com>
Thomas braun dependency-injection_with_robo_guice-presentation-final
{concept}
Inversion of Control (IoC)




      {concept}
Dependency Injection (DI)




Googe Guice                    Spring core   PicoContainer   Plexus




                  Android
RoboGuice                          Dagger
                 Annotations
Dependency Injection (DI)

Makes code ...
● more concise


● more modular


● easier to test
public class GuicelessActivity extends Activity {
…
@Override
  protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);




@ContentView(R.layout.main)
public class GuicyActivity extends RoboActivity {
...
TextView       outputText;
...
outputText =(TextView)findViewById(R.id.text_output);




@InjectView(R.id.text_output) TextView outputText;
String appName;
...
appName = getString(R.string.app_name);




@InjectView(R.id.text_output) TextView outputText;
SensorManager sensorManager;
...
sensorManager
     = (SensorManager)getSystemService(SENSOR_SERVICE);




@Inject SensorManager sensorManager;
SomeController someController;
..
someController = new SomeController(this);




@Inject SomeController someController;



public class SomeController {
  Activity hostActivity;

    @Inject
    public SomeController(Activity hostActivity) {
      this.hostActivity = hostActivity;
    }
}
public class GuicelessActivity extends Activity {
  TextView       outputText;
  String         appName;
  SensorManager sensorManager;
  SomeController someController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      outputText     = (TextView)findViewById(R.id.text_output);
      appName        = getString(R.string.app_name);
      sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
      someController = new SomeController(this);
    }
}




@ContentView(R.layout.main)
public class GuicyActivity extends RoboActivity {
  @InjectView(R.id.text_output)      TextView outputText;
  @InjectResource(R.string.app_name) String appName;
  @Inject                            SensorManager sensorManager;
  @Inject                            SomeController someController;
}
15 LOC → 7 LOC

= more concisene
Dependency Injection (DI)

Makes code ...
● more concise


● more modular


● easier to test
Bindings

public class MyModule extends AbstractModule {

    @Override
    protected void configure() {
      // custom binding go here
    }
}
bind(ISomeService.class).to(SomeServiceDummy.class);
bind(ISomeService.class)
           .toInstance(new SomeServiceReal("yes", 1));
@Inject
@Provides
public AnotherService provideAnotherService(
   ISomeService someService
) {
  return new AnotherService(someService, "bla");
}
Bindings allows for

● wiring up components
● configuring components
Adding
Google Analytics to an Activity
● onCreate → startNewSession


● onResume → trackPageView


● onDestroy → stopSession


● Attributes


● Support code
Component Bloat-Up
● anti pattern: God Class


● low coherence


● tight coupling


● low separation of concernes
public void onCreate(@Observes OnCreateEvent onCreateEvent)
@Inject protected AnalyticsMixin analyticsMixin;
We get:
● loose coupling


● high coherence


● centralized wiring


● centralized configuration
Testability (see wikipedia)
●   controllability: The degree to which it is possible to control the state of the
    component under test (CUT) as required for testing.

●   observability: The degree to which it is possible to observe (intermediate
    and final) test results.

●   isolateability: The degree to which the CUT can be tested in isolation.
●   separation of concerns: The degree to which the CUT has a single,
    well defined responsibility.

●   understandability: The degree to which the CUT is documented or
    self-explaining.

●   automatability: The degree to which it is possible to automate testing of
    the CUT.

●   heterogeneity: The degree to which the use of diverse technologies
    requires to use diverse test methods and tools in parallel.
@RunWith(RobolectricTestRunner.class)
public class SomeServiceTest {
  @Mock private SomeDAO mockDao;
  @Mock private Logger mockLogger;

    private SomeService cut;

    @Before
    public void setUp() throws Exception {
      MockitoAnnotations.initMocks(this);
      cut.someDao = mockDao;
      cut.log = mockLogger;
    }

    @Test
    public void testExecute_willPassWhenNotInBeta() {
      when(mockDao.countSomeStuff()).thenReturn(23);
      assertTrue(cut.hasEnoughStuff());
      verify(mockLogger, times(1)).info("have 23");
    }
}
Testability (see wikipedia)
●   controllability ++
●   observability ++
●   isolateability ++
●   separation of concerns ++
●   understandability +
●   automatability +
●   heterogeneity o
Dependency Injection (DI)

Makes code ...
● more concise


● more modular


● easier to test
References:
●   DI: http://martinfowler.com/articles/injection.html
●   Guice: http://code.google.com/p/google-guice/
●   RoboGuice: https://github.com/roboguice/roboguice
●   Testability:
    http://en.wikipedia.org/wiki/Software_testability
●   Mockito: http://code.google.com/p/mockito/
●   Rebolectric: http://pivotal.github.io/robolectric/


Contact:
●   tom.braun@apps4use.com
●   @tom___b
●   http://play.google.com → GrooveGrid

More Related Content

PDF
Android development
PPTX
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
PPTX
Dependency Injection for Android
PPTX
Dagger 2 - Injeção de Dependência
PDF
My way to clean android V2
PPTX
Developing ASP.NET Applications Using the Model View Controller Pattern
PPTX
Open sourcing the store
PDF
PROMAND 2014 project structure
Android development
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android
Dagger 2 - Injeção de Dependência
My way to clean android V2
Developing ASP.NET Applications Using the Model View Controller Pattern
Open sourcing the store
PROMAND 2014 project structure

What's hot (20)

PDF
GKAC 2015 Apr. - RxAndroid
PDF
My way to clean android v2 English DroidCon Spain
PDF
Software engineering ⊇ Software testing
PDF
Tools & tricks for testing React applications
PPTX
Clean Test
PPTX
Introduction to Struts 2
PDF
Testing in android
PDF
Enterprise Guice 20090217 Bejug
PDF
The Ring programming language version 1.8 book - Part 77 of 202
PDF
Testing Android apps based on Dagger and RxJava
PPTX
Green Custard Friday Talk 21: React Hooks
PDF
The Ring programming language version 1.7 book - Part 75 of 196
PDF
Android Design Patterns
PDF
Advanced Dagger talk from 360andev
PPTX
BizSpark SF Lightning Talk: "Automated Testing (Unit, Integration and Systems...
PDF
"Node.js threads for I/O-bound tasks", Timur Shemsedinov
PDF
Testing Android apps based on Dagger and RxJava Droidcon UK
PPTX
Droidcon Berlin Barcamp 2016
PDF
My way to clean android - Android day salamanca edition
PPTX
Mvp - типичные задачи и способ их решения в Moxy
GKAC 2015 Apr. - RxAndroid
My way to clean android v2 English DroidCon Spain
Software engineering ⊇ Software testing
Tools & tricks for testing React applications
Clean Test
Introduction to Struts 2
Testing in android
Enterprise Guice 20090217 Bejug
The Ring programming language version 1.8 book - Part 77 of 202
Testing Android apps based on Dagger and RxJava
Green Custard Friday Talk 21: React Hooks
The Ring programming language version 1.7 book - Part 75 of 196
Android Design Patterns
Advanced Dagger talk from 360andev
BizSpark SF Lightning Talk: "Automated Testing (Unit, Integration and Systems...
"Node.js threads for I/O-bound tasks", Timur Shemsedinov
Testing Android apps based on Dagger and RxJava Droidcon UK
Droidcon Berlin Barcamp 2016
My way to clean android - Android day salamanca edition
Mvp - типичные задачи и способ их решения в Moxy
Ad

Viewers also liked (20)

PDF
Droidcon 2013 ui smartphones tam hanna
PDF
Roduner democratizing business processes with android-based mobile devices
PDF
ASTD Houston Keynote: The Time to Mobilize Learning is Now! by RJ Jacquez
PDF
Droidcon 2010: Android and iPhone - a known Antagonism ? Professor Dr. Kai Ra...
ODP
Dependency Injection in Spring in 10min
PPS
Introduction To Dependency Injection Using Spring.NET
PPTX
Spring beans
PPT
Spring Core
PDF
Spring and dependency injection
PPTX
Contexts and Dependency Injection
PDF
Mobile GUI Design - Web Designer Magazine Article
PPTX
Dependency injection
PDF
Guice - dependency injection framework
PDF
Introduction to Spring's Dependency Injection
PDF
Clean code via dependency injection + guice
PPTX
Implement Dependency Injection in Java
PPTX
Eway google-guice presentation
PPTX
Spring introduction
PPTX
Spring dependency injection
PDF
Designing and Evaluating a Contextual Mobile Application to Support Situated ...
Droidcon 2013 ui smartphones tam hanna
Roduner democratizing business processes with android-based mobile devices
ASTD Houston Keynote: The Time to Mobilize Learning is Now! by RJ Jacquez
Droidcon 2010: Android and iPhone - a known Antagonism ? Professor Dr. Kai Ra...
Dependency Injection in Spring in 10min
Introduction To Dependency Injection Using Spring.NET
Spring beans
Spring Core
Spring and dependency injection
Contexts and Dependency Injection
Mobile GUI Design - Web Designer Magazine Article
Dependency injection
Guice - dependency injection framework
Introduction to Spring's Dependency Injection
Clean code via dependency injection + guice
Implement Dependency Injection in Java
Eway google-guice presentation
Spring introduction
Spring dependency injection
Designing and Evaluating a Contextual Mobile Application to Support Situated ...
Ad

Similar to Thomas braun dependency-injection_with_robo_guice-presentation-final (20)

PDF
Overview of Android Infrastructure
PDF
Overview of Android Infrastructure
PDF
Android Best Practices
PDF
Improving android experience for both users and developers
PDF
Droidcon2013 android experience lahoda
PDF
Alexey Buzdin "Maslow's Pyramid of Android Testing"
PPTX
Sapphire Gimlets
PPTX
Guice gin
PDF
Devoxx 2012 (v2)
PPTX
[NDC 2019] Enterprise-Grade Serverless
PPTX
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
PDF
droidparts
PDF
Struts2 notes
PDF
droidQuery: The Android port of jQuery
PPT
比XML更好用的Java Annotation
PDF
Spring 3: What's New
PDF
Web UI test automation instruments
PDF
Fragments anyone
PDF
Unit & Automation Testing in Android - Stanislav Gatsev, Melon
Overview of Android Infrastructure
Overview of Android Infrastructure
Android Best Practices
Improving android experience for both users and developers
Droidcon2013 android experience lahoda
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Sapphire Gimlets
Guice gin
Devoxx 2012 (v2)
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
droidparts
Struts2 notes
droidQuery: The Android port of jQuery
比XML更好用的Java Annotation
Spring 3: What's New
Web UI test automation instruments
Fragments anyone
Unit & Automation Testing in Android - Stanislav Gatsev, Melon

More from Droidcon Berlin (20)

PDF
Droidcon de 2014 google cast
PDF
Android programming -_pushing_the_limits
PDF
crashing in style
PDF
Raspberry Pi
PDF
Android industrial mobility
PDF
Details matter in ux
PDF
From sensor data_to_android_and_back
PDF
new_age_graphics_android_x86
PDF
5 tips of monetization
PDF
Testing and Building Android
PDF
Matchinguu droidcon presentation
PDF
Cgm life sdk_droidcon_2014_v3
PDF
The artofcalabash peterkrauss
PDF
Raesch, gries droidcon 2014
PDF
Android open gl2_droidcon_2014
PDF
20140508 quantified self droidcon
PDF
Tuning android for low ram devices
PDF
Froyo to kit kat two years developing & maintaining deliradio
PDF
Droidcon2013 security genes_trendmicro
PDF
Droidcon2013 commercialsuccess rannenberg
Droidcon de 2014 google cast
Android programming -_pushing_the_limits
crashing in style
Raspberry Pi
Android industrial mobility
Details matter in ux
From sensor data_to_android_and_back
new_age_graphics_android_x86
5 tips of monetization
Testing and Building Android
Matchinguu droidcon presentation
Cgm life sdk_droidcon_2014_v3
The artofcalabash peterkrauss
Raesch, gries droidcon 2014
Android open gl2_droidcon_2014
20140508 quantified self droidcon
Tuning android for low ram devices
Froyo to kit kat two years developing & maintaining deliradio
Droidcon2013 security genes_trendmicro
Droidcon2013 commercialsuccess rannenberg

Recently uploaded (20)

PPTX
Probability Distribution, binomial distribution, poisson distribution
PDF
WRN_Investor_Presentation_August 2025.pdf
PPT
Data mining for business intelligence ch04 sharda
PDF
Power and position in leadershipDOC-20250808-WA0011..pdf
PDF
kom-180-proposal-for-a-directive-amending-directive-2014-45-eu-and-directive-...
PDF
How to Get Funding for Your Trucking Business
PPTX
CkgxkgxydkydyldylydlydyldlyddolydyoyyU2.pptx
PDF
How to Get Business Funding for Small Business Fast
PPTX
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
PDF
Reconciliation AND MEMORANDUM RECONCILATION
PPT
340036916-American-Literature-Literary-Period-Overview.ppt
PPTX
ICG2025_ICG 6th steering committee 30-8-24.pptx
DOCX
Business Management - unit 1 and 2
PDF
Katrina Stoneking: Shaking Up the Alcohol Beverage Industry
PDF
Roadmap Map-digital Banking feature MB,IB,AB
PDF
Stem Cell Market Report | Trends, Growth & Forecast 2025-2034
PDF
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
PPTX
Amazon (Business Studies) management studies
PPTX
New Microsoft PowerPoint Presentation - Copy.pptx
PPTX
The Marketing Journey - Tracey Phillips - Marketing Matters 7-2025.pptx
Probability Distribution, binomial distribution, poisson distribution
WRN_Investor_Presentation_August 2025.pdf
Data mining for business intelligence ch04 sharda
Power and position in leadershipDOC-20250808-WA0011..pdf
kom-180-proposal-for-a-directive-amending-directive-2014-45-eu-and-directive-...
How to Get Funding for Your Trucking Business
CkgxkgxydkydyldylydlydyldlyddolydyoyyU2.pptx
How to Get Business Funding for Small Business Fast
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
Reconciliation AND MEMORANDUM RECONCILATION
340036916-American-Literature-Literary-Period-Overview.ppt
ICG2025_ICG 6th steering committee 30-8-24.pptx
Business Management - unit 1 and 2
Katrina Stoneking: Shaking Up the Alcohol Beverage Industry
Roadmap Map-digital Banking feature MB,IB,AB
Stem Cell Market Report | Trends, Growth & Forecast 2025-2034
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
Amazon (Business Studies) management studies
New Microsoft PowerPoint Presentation - Copy.pptx
The Marketing Journey - Tracey Phillips - Marketing Matters 7-2025.pptx

Thomas braun dependency-injection_with_robo_guice-presentation-final

  • 1. Dependency Injection with RoboGuice ©2013 Tom Braun <tom.braun@apps4use.com>
  • 3. {concept} Inversion of Control (IoC) {concept} Dependency Injection (DI) Googe Guice Spring core PicoContainer Plexus Android RoboGuice Dagger Annotations
  • 4. Dependency Injection (DI) Makes code ... ● more concise ● more modular ● easier to test
  • 5. public class GuicelessActivity extends Activity { … @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); @ContentView(R.layout.main) public class GuicyActivity extends RoboActivity {
  • 6. ... TextView outputText; ... outputText =(TextView)findViewById(R.id.text_output); @InjectView(R.id.text_output) TextView outputText;
  • 7. String appName; ... appName = getString(R.string.app_name); @InjectView(R.id.text_output) TextView outputText;
  • 8. SensorManager sensorManager; ... sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); @Inject SensorManager sensorManager;
  • 9. SomeController someController; .. someController = new SomeController(this); @Inject SomeController someController; public class SomeController { Activity hostActivity; @Inject public SomeController(Activity hostActivity) { this.hostActivity = hostActivity; } }
  • 10. public class GuicelessActivity extends Activity { TextView outputText; String appName; SensorManager sensorManager; SomeController someController; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); outputText = (TextView)findViewById(R.id.text_output); appName = getString(R.string.app_name); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); someController = new SomeController(this); } } @ContentView(R.layout.main) public class GuicyActivity extends RoboActivity { @InjectView(R.id.text_output) TextView outputText; @InjectResource(R.string.app_name) String appName; @Inject SensorManager sensorManager; @Inject SomeController someController; }
  • 11. 15 LOC → 7 LOC = more concisene
  • 12. Dependency Injection (DI) Makes code ... ● more concise ● more modular ● easier to test
  • 13. Bindings public class MyModule extends AbstractModule { @Override protected void configure() { // custom binding go here } }
  • 15. bind(ISomeService.class) .toInstance(new SomeServiceReal("yes", 1));
  • 16. @Inject @Provides public AnotherService provideAnotherService( ISomeService someService ) { return new AnotherService(someService, "bla"); }
  • 17. Bindings allows for ● wiring up components ● configuring components
  • 18. Adding Google Analytics to an Activity ● onCreate → startNewSession ● onResume → trackPageView ● onDestroy → stopSession ● Attributes ● Support code
  • 19. Component Bloat-Up ● anti pattern: God Class ● low coherence ● tight coupling ● low separation of concernes
  • 20. public void onCreate(@Observes OnCreateEvent onCreateEvent)
  • 22. We get: ● loose coupling ● high coherence ● centralized wiring ● centralized configuration
  • 23. Testability (see wikipedia) ● controllability: The degree to which it is possible to control the state of the component under test (CUT) as required for testing. ● observability: The degree to which it is possible to observe (intermediate and final) test results. ● isolateability: The degree to which the CUT can be tested in isolation. ● separation of concerns: The degree to which the CUT has a single, well defined responsibility. ● understandability: The degree to which the CUT is documented or self-explaining. ● automatability: The degree to which it is possible to automate testing of the CUT. ● heterogeneity: The degree to which the use of diverse technologies requires to use diverse test methods and tools in parallel.
  • 24. @RunWith(RobolectricTestRunner.class) public class SomeServiceTest { @Mock private SomeDAO mockDao; @Mock private Logger mockLogger; private SomeService cut; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); cut.someDao = mockDao; cut.log = mockLogger; } @Test public void testExecute_willPassWhenNotInBeta() { when(mockDao.countSomeStuff()).thenReturn(23); assertTrue(cut.hasEnoughStuff()); verify(mockLogger, times(1)).info("have 23"); } }
  • 25. Testability (see wikipedia) ● controllability ++ ● observability ++ ● isolateability ++ ● separation of concerns ++ ● understandability + ● automatability + ● heterogeneity o
  • 26. Dependency Injection (DI) Makes code ... ● more concise ● more modular ● easier to test
  • 27. References: ● DI: http://martinfowler.com/articles/injection.html ● Guice: http://code.google.com/p/google-guice/ ● RoboGuice: https://github.com/roboguice/roboguice ● Testability: http://en.wikipedia.org/wiki/Software_testability ● Mockito: http://code.google.com/p/mockito/ ● Rebolectric: http://pivotal.github.io/robolectric/ Contact: ● tom.braun@apps4use.com ● @tom___b ● http://play.google.com → GrooveGrid