SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Slaying Sacred Cows:
Deconstructing
Dependency Injection
Tomer Gabel
Full Disclosure
• I was never a fan
• I tried researching
this properly…
– Read a ton of material
– Interviewed people
– Sat and thought
• Still turned out a rant
Image: ImgFlip
Semantics
When I say “dependency injection”, you’re
probably thinking of this:
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
bind(CreditCardProcessor.class).to(PaypalCreditCardProcessor.class);
}
}
So did I.
1. THE “D” IN SOLID
Image: Peter von Bagh, “Just Frozen Water” via Flickr (CC0 1.0 Public Domain)
Back to Basics
• Single responsibility
• Open/closed
• Liskov substitution principle
• Interface segregation
• Dependency inversion
Image: Michael Feathers via MozaicWorks
Back to Basics
• Single responsibility
• Open/closed
• Liskov substitution principle
• Interface segregation
• Dependency inversion
Image: Michael Feathers via MozaicWorks
Dependency Inversion
• A simple idea
• Given a dependency:
– A must not depend on B
directly
OAuthProvider
MysqlUserStore
“A”
“B”
Dependency Inversion
• A simple idea
• Given a dependency:
– A must not depend on B
directly
– Instead, A depends on
an abstraction of B
– B depends on the
same abstraction
OAuthProvider
MysqlUserStore
UserStore
class
class
interface
“A”
“B”
The Verdict
• Dependency
inversion is old hat
– Seems obvious now
– First postulated by
Uncle Bob in 1994 (!)
• We’ve come a long
way since!
“The philosophy of
one century is the
common sense
of the next.”
-- Henry Ward
Beecher
Image: Mathew Brady, “Henry Ward Beecher” via Library of Congress (Public Domain)
2. DECOUPLE
ME SOFTLY
Image: Mark Menzies, “Le Chav Sportif” via Flickr (CC-BY-NC-SA 2.0)
Dependency Injection
• Let’s assume SOLID…
• Given a dependency:
– Who owns it?
– What is the lifecycle?
• Traditionally:
– The depending service
manages everything
class UserService {
private UserStore store =
new MysqlUserStore(Config.JDBC_URL);
bool authenticate(String userToken) {
UserContext user =
store.lookup(userToken);
return user != null
? user.isActive()
: false;
}
}
Dependency Injection
• DI stipulates:
– Services should not
build dependencies
– But instead receive them
– Dependencies are state
• It does not stipulate
how to implement this
class UserService {
private UserStore store;
public UserService(UserStore store) {
this.store = store;
}
bool authenticate(String userToken) {
// ...
}
}
The Verdict
• Dependency
injection is good
• If taken at face value:
– No frameworks
– No containers
– No reflection
– Simply common sense
Image: Tomas Catelazo via Wikimedia Commons (CC-BY-SA 4.0)
3. THINGS
GET HAIRY
Image: Matt Acevedo, “Alpaca” via Flickr (CC-BY 2.0)
Inversion of Control
• IoC is not a pattern
• It’s a design principle
• Traditionally:
– “Main” flow calls into
components
– Control flows back to
the “main” flow
Main (entry point)
• Configuration
• Bootstrapping
Event loop
• Dequeue
• Dispatch
Event handler
• Act on event
• Done
Inversion of Control
• IoC is not a pattern
• It’s a design principle
• With IoC:
– Control is surrendered
to a container
– Container calls into
components
Main (entry point)
• Setup
IoC container
• Bootstrapping/wiring
• Event loop
Event handler
• Act on event
• Done
Inversion of Control
• IoC means many things
– Servlet containers
– Plugin systems
– Stream computing
– “DI” containers
• We’ll focus on the latter
IoC & DI
• Consider Spring/Guice
– A runtime container
– Manages components
– … including lifecycle
– … and automatic wiring
Image: ImgFlip
Perceived Benefits
• Why use a container?
– Simplify wiring
– Simplify testing
– Dynamic configuration
– Support for AOP
• Let’s consider each
Image: ImgFlip
Perceived Benefits
• Why use a container?
– Simplify wiring
– Simplify testing
– Dynamic configuration
– Support for AOP
• Let’s consider each
Image: ImgFlip
Simplified Wiring
class MyApp {
DBI db = new DBIFactory().build(...);
EventStore eventStore =
new MysqlEventStore(db);
SnapshotStore snapshotStore =
new MysqlSnapshotStore(db);
Clock clock =
Clock.systemUTC();
SiteService siteService =
new DefaultSiteService(
eventStore, snapshotStore, clock);
}
Simplified Wiring
class MyApp {
DBI db = new DBIFactory().build(...);
EventStore eventStore =
new MysqlEventStore(db);
SnapshotStore snapshotStore =
new MysqlSnapshotStore(db);
Clock clock =
Clock.systemUTC();
SiteService siteService =
new DefaultSiteService(
eventStore, snapshotStore, clock);
}
class MyAppModule extends AbstractModule {
@Override
protected void configure() {
bind(DBI.class).toProvider(...);
bind(EventStore.class)
.to(MysqlEventStore.class);
bind(SnapshotStore.class)
.to(MysqlSnapshotStore.class);
bind(Clock.class)
.toProvider(Clock::systemUTC);
bind(SiteService.class)
.to(DefaultSiteService.class);
}
}
Simplified Wiring
class MyApp {
DBI db = new DBIFactory().build(...);
EventStore eventStore =
new MysqlEventStore(db);
SnapshotStore snapshotStore =
new MysqlSnapshotStore(db);
Clock clock =
Clock.systemUTC();
SiteService siteService =
new DefaultSiteService(
eventStore, snapshotStore, clock);
}
class MyAppModule extends AbstractModule {
@Override
protected void configure() {
bind(DBI.class).toProvider(...);
bind(EventStore.class)
.to(MysqlEventStore.class);
bind(SnapshotStore.class)
.to(MysqlSnapshotStore.class);
bind(Clock.class)
.toProvider(Clock::systemUTC);
bind(SiteService.class)
.to(DefaultSiteService.class);
}
}
Simplified Wiring
• No tangible benefit!
– Wiring is trivial
• Real, tangible downsides
– Startup time
– Code navigability
– Dynamic/reflective magic
Image: André Nordstrand, “Loss of common sense” via Flickr (CC-BY-NC 2.0)
Simplify Testing
• Proponents will tell you:
1. Bring up a container
2. Swap out components
3. Bob’s your uncle
Simplify Testing
deconstruction (source: dictionary.com)
Noun
1. a technique of literary analysis that regards
meaning as resulting from the differences
between words rather than their reference to
the things they stand for.
Simplify Testing
• Congratulations!
• You’re doing
deconstructive
testing
Wha-huh?
Constructive testing Deconstructive testing
MysqlEventStore
DataSource
SiteService
MysqlEventStore
DataSource
MysqlSnapshotStore
DataSource
Clock
Wha-huh?
Constructive testing Deconstructive testing
MysqlEventStore
DataSource
SiteService
MysqlEventStore
DataSource
MockSnapshotStore
Fixed
Clock
Simplify Testing
• This is a bad idea
– Hard to reason about
– Have to deal with
subtle interactions
– Does not reflect your
unit structure
• Most importantly…
– Leads to poor design!
Image: Viewminder, “Strange Bedfellows” via Flickr (CC-BY-NC-ND 2.0)
IN SUMMARY…
IoC is a solution in
search of a problem
… except …
• With huge codebases
– Read: “Monoliths”
– Read: “Enterprise”
• Enables a tradeoff
– Developer discipline
– Code coherence,
simplicity, navigability
… except …
• With huge codebases
– Read: “Monoliths”
– Read: “Enterprise”
• Enables a tradeoff
– Developer discipline
– Code coherence,
simplicity, navigability
Corollary:
If you’re seeing
benefit from IoC,
your codebase is
already out of
control.
QUESTIONS?
Thank you for listening
tomer@tomergabel.com
@tomerg
http://engineering.wix.com
Sample Project:
http://tinyurl.com/event-sourcing-sample
This work is licensed under a Creative
Commons Attribution-ShareAlike 4.0
International License.

Weitere ähnliche Inhalte

Was ist angesagt?

OpenStack 101 - All Things Open 2015
OpenStack 101 - All Things Open 2015OpenStack 101 - All Things Open 2015
OpenStack 101 - All Things Open 2015Mark Voelker
 
Planning to Fail #phpne13
Planning to Fail #phpne13Planning to Fail #phpne13
Planning to Fail #phpne13Dave Gardner
 
OpenStack: Toward a More Resilient Cloud
OpenStack: Toward a More Resilient CloudOpenStack: Toward a More Resilient Cloud
OpenStack: Toward a More Resilient CloudMark Voelker
 
NYC Cassandra Day - Java Intro
NYC Cassandra Day - Java IntroNYC Cassandra Day - Java Intro
NYC Cassandra Day - Java IntroChristopher Batey
 
DefCore: The Interoperability Standard for OpenStack
DefCore: The Interoperability Standard for OpenStackDefCore: The Interoperability Standard for OpenStack
DefCore: The Interoperability Standard for OpenStackMark Voelker
 
Luc Dekens - Italian vmug usercon
Luc Dekens - Italian vmug usercon Luc Dekens - Italian vmug usercon
Luc Dekens - Italian vmug usercon VMUG IT
 
Interoperability: The Elephants in the Room & What We're Doing About Them
Interoperability: The Elephants in the Room & What We're Doing About ThemInteroperability: The Elephants in the Room & What We're Doing About Them
Interoperability: The Elephants in the Room & What We're Doing About ThemMark Voelker
 
OpenNebulaConf2015 1.07 Cloud for Scientific Computing @ STFC - Alexander Dibbo
OpenNebulaConf2015 1.07 Cloud for Scientific Computing @ STFC - Alexander DibboOpenNebulaConf2015 1.07 Cloud for Scientific Computing @ STFC - Alexander Dibbo
OpenNebulaConf2015 1.07 Cloud for Scientific Computing @ STFC - Alexander DibboOpenNebula Project
 
Opscode-Eucalyptus Webinar 20110721
 Opscode-Eucalyptus Webinar 20110721 Opscode-Eucalyptus Webinar 20110721
Opscode-Eucalyptus Webinar 20110721Chef Software, Inc.
 
Micronaut For Single Page Apps
Micronaut For Single Page AppsMicronaut For Single Page Apps
Micronaut For Single Page AppsZachary Klein
 
OpenStack + VMware: Deploy, Upgrade, & Operate a Powerful Production OpenStac...
OpenStack + VMware: Deploy, Upgrade, & Operate a Powerful Production OpenStac...OpenStack + VMware: Deploy, Upgrade, & Operate a Powerful Production OpenStac...
OpenStack + VMware: Deploy, Upgrade, & Operate a Powerful Production OpenStac...Mark Voelker
 
LJC: Microservices in the real world
LJC: Microservices in the real worldLJC: Microservices in the real world
LJC: Microservices in the real worldChristopher Batey
 
server to cloud: converting a legacy platform to an open source paas
server to cloud:  converting a legacy platform to an open source paasserver to cloud:  converting a legacy platform to an open source paas
server to cloud: converting a legacy platform to an open source paasTodd Fritz
 
Planning to Fail #phpuk13
Planning to Fail #phpuk13Planning to Fail #phpuk13
Planning to Fail #phpuk13Dave Gardner
 
vBrownBag - Scripting and Versioning with PowerShell ISE and Git Shell
vBrownBag - Scripting and Versioning with PowerShell ISE and Git ShellvBrownBag - Scripting and Versioning with PowerShell ISE and Git Shell
vBrownBag - Scripting and Versioning with PowerShell ISE and Git ShellChris Wahl
 
Novalug 07142012
Novalug 07142012Novalug 07142012
Novalug 07142012Mandi Walls
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 
(SCALE 12x) OpenStack vs. VMware - A System Administrator Perspective
(SCALE 12x) OpenStack vs. VMware - A System Administrator Perspective(SCALE 12x) OpenStack vs. VMware - A System Administrator Perspective
(SCALE 12x) OpenStack vs. VMware - A System Administrator PerspectiveStackStorm
 
Skipping OpenStack Releases: (You Don't) Gotta Catch 'Em All
Skipping OpenStack Releases: (You Don't) Gotta Catch 'Em AllSkipping OpenStack Releases: (You Don't) Gotta Catch 'Em All
Skipping OpenStack Releases: (You Don't) Gotta Catch 'Em AllMark Voelker
 

Was ist angesagt? (20)

OpenStack 101 - All Things Open 2015
OpenStack 101 - All Things Open 2015OpenStack 101 - All Things Open 2015
OpenStack 101 - All Things Open 2015
 
Planning to Fail #phpne13
Planning to Fail #phpne13Planning to Fail #phpne13
Planning to Fail #phpne13
 
OpenStack: Toward a More Resilient Cloud
OpenStack: Toward a More Resilient CloudOpenStack: Toward a More Resilient Cloud
OpenStack: Toward a More Resilient Cloud
 
NYC Cassandra Day - Java Intro
NYC Cassandra Day - Java IntroNYC Cassandra Day - Java Intro
NYC Cassandra Day - Java Intro
 
DefCore: The Interoperability Standard for OpenStack
DefCore: The Interoperability Standard for OpenStackDefCore: The Interoperability Standard for OpenStack
DefCore: The Interoperability Standard for OpenStack
 
Luc Dekens - Italian vmug usercon
Luc Dekens - Italian vmug usercon Luc Dekens - Italian vmug usercon
Luc Dekens - Italian vmug usercon
 
Interoperability: The Elephants in the Room & What We're Doing About Them
Interoperability: The Elephants in the Room & What We're Doing About ThemInteroperability: The Elephants in the Room & What We're Doing About Them
Interoperability: The Elephants in the Room & What We're Doing About Them
 
OpenNebulaConf2015 1.07 Cloud for Scientific Computing @ STFC - Alexander Dibbo
OpenNebulaConf2015 1.07 Cloud for Scientific Computing @ STFC - Alexander DibboOpenNebulaConf2015 1.07 Cloud for Scientific Computing @ STFC - Alexander Dibbo
OpenNebulaConf2015 1.07 Cloud for Scientific Computing @ STFC - Alexander Dibbo
 
Opscode-Eucalyptus Webinar 20110721
 Opscode-Eucalyptus Webinar 20110721 Opscode-Eucalyptus Webinar 20110721
Opscode-Eucalyptus Webinar 20110721
 
Micronaut For Single Page Apps
Micronaut For Single Page AppsMicronaut For Single Page Apps
Micronaut For Single Page Apps
 
OpenStack + VMware: Deploy, Upgrade, & Operate a Powerful Production OpenStac...
OpenStack + VMware: Deploy, Upgrade, & Operate a Powerful Production OpenStac...OpenStack + VMware: Deploy, Upgrade, & Operate a Powerful Production OpenStac...
OpenStack + VMware: Deploy, Upgrade, & Operate a Powerful Production OpenStac...
 
LJC: Microservices in the real world
LJC: Microservices in the real worldLJC: Microservices in the real world
LJC: Microservices in the real world
 
Openstack 101
Openstack 101Openstack 101
Openstack 101
 
server to cloud: converting a legacy platform to an open source paas
server to cloud:  converting a legacy platform to an open source paasserver to cloud:  converting a legacy platform to an open source paas
server to cloud: converting a legacy platform to an open source paas
 
Planning to Fail #phpuk13
Planning to Fail #phpuk13Planning to Fail #phpuk13
Planning to Fail #phpuk13
 
vBrownBag - Scripting and Versioning with PowerShell ISE and Git Shell
vBrownBag - Scripting and Versioning with PowerShell ISE and Git ShellvBrownBag - Scripting and Versioning with PowerShell ISE and Git Shell
vBrownBag - Scripting and Versioning with PowerShell ISE and Git Shell
 
Novalug 07142012
Novalug 07142012Novalug 07142012
Novalug 07142012
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
(SCALE 12x) OpenStack vs. VMware - A System Administrator Perspective
(SCALE 12x) OpenStack vs. VMware - A System Administrator Perspective(SCALE 12x) OpenStack vs. VMware - A System Administrator Perspective
(SCALE 12x) OpenStack vs. VMware - A System Administrator Perspective
 
Skipping OpenStack Releases: (You Don't) Gotta Catch 'Em All
Skipping OpenStack Releases: (You Don't) Gotta Catch 'Em AllSkipping OpenStack Releases: (You Don't) Gotta Catch 'Em All
Skipping OpenStack Releases: (You Don't) Gotta Catch 'Em All
 

Ähnlich wie Slaying Sacred Cows: Deconstructing Dependency Injection

Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applicationsIvano Malavolta
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!Roberto Messora
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSAkshay Mathur
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4Naga Muruga
 
Dropwizard Restful 微服務 (microservice) 初探 - JCConf TW 2014
Dropwizard Restful 微服務 (microservice) 初探 - JCConf TW 2014Dropwizard Restful 微服務 (microservice) 初探 - JCConf TW 2014
Dropwizard Restful 微服務 (microservice) 初探 - JCConf TW 2014Anthony Chen
 
Advanced #6 clean architecture
Advanced #6  clean architectureAdvanced #6  clean architecture
Advanced #6 clean architectureVitali Pekelis
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaXamarin
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO DevsWO Community
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014FalafelSoftware
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...smn-automate
 
Salesforce lwc development workshops session #6
Salesforce lwc development workshops  session #6Salesforce lwc development workshops  session #6
Salesforce lwc development workshops session #6Rahul Gawale
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersAoteaStudios
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Managementstable|kernel
 
Coldbox developer training – session 5
Coldbox developer training – session 5Coldbox developer training – session 5
Coldbox developer training – session 5Billie Berzinskas
 

Ähnlich wie Slaying Sacred Cows: Deconstructing Dependency Injection (20)

Developing maintainable Cordova applications
Developing maintainable Cordova applicationsDeveloping maintainable Cordova applications
Developing maintainable Cordova applications
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Group111
Group111Group111
Group111
 
MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!MV* presentation frameworks in Javascript: en garde, pret, allez!
MV* presentation frameworks in Javascript: en garde, pret, allez!
 
Creating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JSCreating Single Page Web App using Backbone JS
Creating Single Page Web App using Backbone JS
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4
 
Dropwizard Restful 微服務 (microservice) 初探 - JCConf TW 2014
Dropwizard Restful 微服務 (microservice) 初探 - JCConf TW 2014Dropwizard Restful 微服務 (microservice) 初探 - JCConf TW 2014
Dropwizard Restful 微服務 (microservice) 初探 - JCConf TW 2014
 
Advanced #6 clean architecture
Advanced #6  clean architectureAdvanced #6  clean architecture
Advanced #6 clean architecture
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
 
Apache Cayenne for WO Devs
Apache Cayenne for WO DevsApache Cayenne for WO Devs
Apache Cayenne for WO Devs
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
 
Salesforce lwc development workshops session #6
Salesforce lwc development workshops  session #6Salesforce lwc development workshops  session #6
Salesforce lwc development workshops session #6
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developers
 
Liferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for DevelopersLiferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for Developers
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Management
 
Backbonejs
BackbonejsBackbonejs
Backbonejs
 
Coldbox developer training – session 5
Coldbox developer training – session 5Coldbox developer training – session 5
Coldbox developer training – session 5
 

Mehr von Tomer Gabel

How shit works: Time
How shit works: TimeHow shit works: Time
How shit works: TimeTomer Gabel
 
Nondeterministic Software for the Rest of Us
Nondeterministic Software for the Rest of UsNondeterministic Software for the Rest of Us
Nondeterministic Software for the Rest of UsTomer Gabel
 
How shit works: the CPU
How shit works: the CPUHow shit works: the CPU
How shit works: the CPUTomer Gabel
 
How Shit Works: Storage
How Shit Works: StorageHow Shit Works: Storage
How Shit Works: StorageTomer Gabel
 
Java 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryJava 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryTomer Gabel
 
The Wix Microservice Stack
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice StackTomer Gabel
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Tomer Gabel
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitTomer Gabel
 
Onboarding at Scale
Onboarding at ScaleOnboarding at Scale
Onboarding at ScaleTomer Gabel
 
Scala in the Wild
Scala in the WildScala in the Wild
Scala in the WildTomer Gabel
 
Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Tomer Gabel
 
Put Your Thinking CAP On
Put Your Thinking CAP OnPut Your Thinking CAP On
Put Your Thinking CAP OnTomer Gabel
 
Leveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationTomer Gabel
 
A Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaTomer Gabel
 
Functional Leap of Faith (Keynote at JDay Lviv 2014)
Functional Leap of Faith (Keynote at JDay Lviv 2014)Functional Leap of Faith (Keynote at JDay Lviv 2014)
Functional Leap of Faith (Keynote at JDay Lviv 2014)Tomer Gabel
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
5 Bullets to Scala Adoption
5 Bullets to Scala Adoption5 Bullets to Scala Adoption
5 Bullets to Scala AdoptionTomer Gabel
 
Nashorn: JavaScript that doesn’t suck (ILJUG)
Nashorn: JavaScript that doesn’t suck (ILJUG)Nashorn: JavaScript that doesn’t suck (ILJUG)
Nashorn: JavaScript that doesn’t suck (ILJUG)Tomer Gabel
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With ScalaTomer Gabel
 
Lab: JVM Production Debugging 101
Lab: JVM Production Debugging 101Lab: JVM Production Debugging 101
Lab: JVM Production Debugging 101Tomer Gabel
 

Mehr von Tomer Gabel (20)

How shit works: Time
How shit works: TimeHow shit works: Time
How shit works: Time
 
Nondeterministic Software for the Rest of Us
Nondeterministic Software for the Rest of UsNondeterministic Software for the Rest of Us
Nondeterministic Software for the Rest of Us
 
How shit works: the CPU
How shit works: the CPUHow shit works: the CPU
How shit works: the CPU
 
How Shit Works: Storage
How Shit Works: StorageHow Shit Works: Storage
How Shit Works: Storage
 
Java 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryJava 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala Story
 
The Wix Microservice Stack
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice Stack
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
 
Onboarding at Scale
Onboarding at ScaleOnboarding at Scale
Onboarding at Scale
 
Scala in the Wild
Scala in the WildScala in the Wild
Scala in the Wild
 
Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)
 
Put Your Thinking CAP On
Put Your Thinking CAP OnPut Your Thinking CAP On
Put Your Thinking CAP On
 
Leveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better Validation
 
A Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in Scala
 
Functional Leap of Faith (Keynote at JDay Lviv 2014)
Functional Leap of Faith (Keynote at JDay Lviv 2014)Functional Leap of Faith (Keynote at JDay Lviv 2014)
Functional Leap of Faith (Keynote at JDay Lviv 2014)
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
5 Bullets to Scala Adoption
5 Bullets to Scala Adoption5 Bullets to Scala Adoption
5 Bullets to Scala Adoption
 
Nashorn: JavaScript that doesn’t suck (ILJUG)
Nashorn: JavaScript that doesn’t suck (ILJUG)Nashorn: JavaScript that doesn’t suck (ILJUG)
Nashorn: JavaScript that doesn’t suck (ILJUG)
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
 
Lab: JVM Production Debugging 101
Lab: JVM Production Debugging 101Lab: JVM Production Debugging 101
Lab: JVM Production Debugging 101
 

Kürzlich hochgeladen

School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Servicemeghakumariji156
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxSCMS School of Architecture
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 

Kürzlich hochgeladen (20)

School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 

Slaying Sacred Cows: Deconstructing Dependency Injection

  • 2. Full Disclosure • I was never a fan • I tried researching this properly… – Read a ton of material – Interviewed people – Sat and thought • Still turned out a rant Image: ImgFlip
  • 3. Semantics When I say “dependency injection”, you’re probably thinking of this: public class BillingModule extends AbstractModule { @Override protected void configure() { bind(TransactionLog.class).to(DatabaseTransactionLog.class); bind(CreditCardProcessor.class).to(PaypalCreditCardProcessor.class); } } So did I.
  • 4. 1. THE “D” IN SOLID Image: Peter von Bagh, “Just Frozen Water” via Flickr (CC0 1.0 Public Domain)
  • 5. Back to Basics • Single responsibility • Open/closed • Liskov substitution principle • Interface segregation • Dependency inversion Image: Michael Feathers via MozaicWorks
  • 6. Back to Basics • Single responsibility • Open/closed • Liskov substitution principle • Interface segregation • Dependency inversion Image: Michael Feathers via MozaicWorks
  • 7. Dependency Inversion • A simple idea • Given a dependency: – A must not depend on B directly OAuthProvider MysqlUserStore “A” “B”
  • 8. Dependency Inversion • A simple idea • Given a dependency: – A must not depend on B directly – Instead, A depends on an abstraction of B – B depends on the same abstraction OAuthProvider MysqlUserStore UserStore class class interface “A” “B”
  • 9. The Verdict • Dependency inversion is old hat – Seems obvious now – First postulated by Uncle Bob in 1994 (!) • We’ve come a long way since! “The philosophy of one century is the common sense of the next.” -- Henry Ward Beecher Image: Mathew Brady, “Henry Ward Beecher” via Library of Congress (Public Domain)
  • 10. 2. DECOUPLE ME SOFTLY Image: Mark Menzies, “Le Chav Sportif” via Flickr (CC-BY-NC-SA 2.0)
  • 11. Dependency Injection • Let’s assume SOLID… • Given a dependency: – Who owns it? – What is the lifecycle? • Traditionally: – The depending service manages everything class UserService { private UserStore store = new MysqlUserStore(Config.JDBC_URL); bool authenticate(String userToken) { UserContext user = store.lookup(userToken); return user != null ? user.isActive() : false; } }
  • 12. Dependency Injection • DI stipulates: – Services should not build dependencies – But instead receive them – Dependencies are state • It does not stipulate how to implement this class UserService { private UserStore store; public UserService(UserStore store) { this.store = store; } bool authenticate(String userToken) { // ... } }
  • 13. The Verdict • Dependency injection is good • If taken at face value: – No frameworks – No containers – No reflection – Simply common sense Image: Tomas Catelazo via Wikimedia Commons (CC-BY-SA 4.0)
  • 14. 3. THINGS GET HAIRY Image: Matt Acevedo, “Alpaca” via Flickr (CC-BY 2.0)
  • 15. Inversion of Control • IoC is not a pattern • It’s a design principle • Traditionally: – “Main” flow calls into components – Control flows back to the “main” flow Main (entry point) • Configuration • Bootstrapping Event loop • Dequeue • Dispatch Event handler • Act on event • Done
  • 16. Inversion of Control • IoC is not a pattern • It’s a design principle • With IoC: – Control is surrendered to a container – Container calls into components Main (entry point) • Setup IoC container • Bootstrapping/wiring • Event loop Event handler • Act on event • Done
  • 17. Inversion of Control • IoC means many things – Servlet containers – Plugin systems – Stream computing – “DI” containers • We’ll focus on the latter
  • 18. IoC & DI • Consider Spring/Guice – A runtime container – Manages components – … including lifecycle – … and automatic wiring Image: ImgFlip
  • 19. Perceived Benefits • Why use a container? – Simplify wiring – Simplify testing – Dynamic configuration – Support for AOP • Let’s consider each Image: ImgFlip
  • 20. Perceived Benefits • Why use a container? – Simplify wiring – Simplify testing – Dynamic configuration – Support for AOP • Let’s consider each Image: ImgFlip
  • 21. Simplified Wiring class MyApp { DBI db = new DBIFactory().build(...); EventStore eventStore = new MysqlEventStore(db); SnapshotStore snapshotStore = new MysqlSnapshotStore(db); Clock clock = Clock.systemUTC(); SiteService siteService = new DefaultSiteService( eventStore, snapshotStore, clock); }
  • 22. Simplified Wiring class MyApp { DBI db = new DBIFactory().build(...); EventStore eventStore = new MysqlEventStore(db); SnapshotStore snapshotStore = new MysqlSnapshotStore(db); Clock clock = Clock.systemUTC(); SiteService siteService = new DefaultSiteService( eventStore, snapshotStore, clock); } class MyAppModule extends AbstractModule { @Override protected void configure() { bind(DBI.class).toProvider(...); bind(EventStore.class) .to(MysqlEventStore.class); bind(SnapshotStore.class) .to(MysqlSnapshotStore.class); bind(Clock.class) .toProvider(Clock::systemUTC); bind(SiteService.class) .to(DefaultSiteService.class); } }
  • 23. Simplified Wiring class MyApp { DBI db = new DBIFactory().build(...); EventStore eventStore = new MysqlEventStore(db); SnapshotStore snapshotStore = new MysqlSnapshotStore(db); Clock clock = Clock.systemUTC(); SiteService siteService = new DefaultSiteService( eventStore, snapshotStore, clock); } class MyAppModule extends AbstractModule { @Override protected void configure() { bind(DBI.class).toProvider(...); bind(EventStore.class) .to(MysqlEventStore.class); bind(SnapshotStore.class) .to(MysqlSnapshotStore.class); bind(Clock.class) .toProvider(Clock::systemUTC); bind(SiteService.class) .to(DefaultSiteService.class); } }
  • 24. Simplified Wiring • No tangible benefit! – Wiring is trivial • Real, tangible downsides – Startup time – Code navigability – Dynamic/reflective magic Image: André Nordstrand, “Loss of common sense” via Flickr (CC-BY-NC 2.0)
  • 25. Simplify Testing • Proponents will tell you: 1. Bring up a container 2. Swap out components 3. Bob’s your uncle
  • 26. Simplify Testing deconstruction (source: dictionary.com) Noun 1. a technique of literary analysis that regards meaning as resulting from the differences between words rather than their reference to the things they stand for.
  • 27. Simplify Testing • Congratulations! • You’re doing deconstructive testing
  • 28. Wha-huh? Constructive testing Deconstructive testing MysqlEventStore DataSource SiteService MysqlEventStore DataSource MysqlSnapshotStore DataSource Clock
  • 29. Wha-huh? Constructive testing Deconstructive testing MysqlEventStore DataSource SiteService MysqlEventStore DataSource MockSnapshotStore Fixed Clock
  • 30. Simplify Testing • This is a bad idea – Hard to reason about – Have to deal with subtle interactions – Does not reflect your unit structure • Most importantly… – Leads to poor design! Image: Viewminder, “Strange Bedfellows” via Flickr (CC-BY-NC-ND 2.0)
  • 31. IN SUMMARY… IoC is a solution in search of a problem
  • 32. … except … • With huge codebases – Read: “Monoliths” – Read: “Enterprise” • Enables a tradeoff – Developer discipline – Code coherence, simplicity, navigability
  • 33. … except … • With huge codebases – Read: “Monoliths” – Read: “Enterprise” • Enables a tradeoff – Developer discipline – Code coherence, simplicity, navigability Corollary: If you’re seeing benefit from IoC, your codebase is already out of control.
  • 34. QUESTIONS? Thank you for listening tomer@tomergabel.com @tomerg http://engineering.wix.com Sample Project: http://tinyurl.com/event-sourcing-sample This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.