SlideShare a Scribd company logo
Table of Contents
Table of Contents........................................................................................................................................ i
Instructors Biographies.............................................................................................................................. ii
Agenda...................................................................................................................................................... iii
Objectives Of the Course.......................................................................................................................... iv
1Setting Up Environment...........................................................................................................................6
   1.1Setting up Mercurial.........................................................................................................................6
   1.2Setting up Your Favorite Text Editor or Eclipse...............................................................................6
   1.3Getting the Source............................................................................................................................ 6
   1.4Setting up Test Runner..................................................................................................................... 8
2Understanding Manual Dependency Injection.......................................................................................10
   2.1Application wiring diagram............................................................................................................10
   2.2Understanding the Need for DI...................................................................................................... 10
3Designing Automated Dependency Injection Framework..................................................................... 12
   3.1Replacing the Lost Information Of Declared Types.......................................................................12
   3.2Ability to Inject Types.................................................................................................................... 12
   3.3Ability to Inject DOM Elements.................................................................................................... 14
   3.4Ability to Inject Events...................................................................................................................14
4Implementing the Framework................................................................................................................ 16
5Comparing the Resulting Wiring Code.................................................................................................. 18




OOPSLA 2009 Tutorial                                                           i                                                         Miško Hevery
Instructors Biographies

Miško Hevery
misko@hevery.com
Google, Inc.


… works as an Agile Coach at Google where he is responsible for coaching Googlers to maintain the
high level of automated testing culture. This allows Google to do frequent releases of its web
applications with consistent high quality. Previously he worked at Adobe, Sun Microsystems, Intel, and
Xerox (to name a few), where he became an expert in building web applications in web related
technologies such as Java, JavaScript, Flex and ActionScript. He is very involved in Open Source
community and an author of several open source projects. Recently his interest in Test-Driven-
Development turned into Testability Explorer (http://code.google.com/p/testability-explorer) and
JsTestDriver (http://code.google.com/p/js-test-driver) with which he hopes to change the testing culture
of the open source community.




OOPSLA 2009 Tutorial                               ii                                     Miško Hevery
Agenda
   1. Setting up your environment
      1. Setting up Mercurial
      2. Setting up your favorite text editor or Eclipse
      3. Setting up JsTestRunner
   2. Getting the source
      1. Checking out the source code
      2. Running the code
   3. Understanding manual Dependency Injection
      1. Application wiring diagram
      2. Understanding the need for DI
   4. Designing automated Dependency Injection framework
      1. Replacing the lost information of declared types
      2. Injecting types
      3. Injecting DOM elements
      4. Injecting events
   5. Implementing the framework
   6. Cleaning up the bootstrap wiring code
   7. Discussion of before and after code




OOPSLA 2009 Tutorial                              iii       Miško Hevery
Objectives of the Course
Dependency Injection is a good practice even in dynamic languages. Because many dynamic languages
do not have type declarations, building an automatic DI framework presents its own set of challenges.
Furthermore, many concepts, such as scopes that are often associated with threads, change their
meaning in most dynamic languages which are single threaded. In this tutorial, we will build a simple
automatic DI framework and solve many of the challenges which are associated with lack of declared
types in such languages.

   •   Understand the need for Dependency Injection
       ◦ Dynamic languages are not special and still need Dependency Injection
   •   How to replace the lack of typing information in dynamic languages
   •   Injection is not limited to injecting object instances
       ◦ Building our own domain specific language
       ◦ The obvious: Injecting types
       ◦ Thinking outside the box: Injecting DOM elements, and events
   •   Dependency Injection simplifies the wiring of the application logic
       ◦ Comparing application bootstrap process before and after




OOPSLA 2009 Tutorial                             iv                                    Miško Hevery
1 Setting Up Environment
Before the tutorial we recommend that you complete all of the following steps:

1.1 Setting up Mercurial
The code for this project is located at:
   •   http://bitbucket.org/misko/misko-hevery-oopsla-09
You will need to install Mercurial for your platform:
   •   Home: http://mercurial.selenic.com/wiki/
   •   Download: http://mercurial.selenic.com/wiki/Download?
       action=show&redirect=BinaryPackages

1.2 Getting the Source
After installing a copy of Mercurial you can download the source using the following command:
   $ hg clone https://misko@bitbucket.org/misko/misko-hevery-oopsla-09/


1.3 Setting up Your Favorite Text Editor or Eclipse
You will need you favorite Text Editor for editing JavaScript, HTML, and CSS. We recommend Eclipse
which you can download and install from the link bellow. We have already set up an Eclipse workspace
for you in the Mercurial repository.
   •   Download Eclipse: http://www.eclipse.org/downloads/
   •   Install JavaScript Editor: From Eclipse
       ◦ Help → Install New Software
       ◦ Select: Work With: Galileo
       ◦ Select: Web, XML, and Java EE Development
       ◦ Complete the installation by clicking the “Next” button
   •   Install JsTestDriver for Eclipse
       ◦ Help → Install New Software
       ◦ Select: Work With: and enter: http://js-test-driver.googlecode.com/svn/update/
       ◦ Select JsTestDriver
       ◦ Complete the installation by clicking the “Next” button
   •   Import the DI project which you downloaded with Mercurial.




OOPSLA 2009 Tutorial                                                                      Miško Hevery
1.4 Setting up Test Runner
NOTE: All commands need to be executed from the root of the source code which you downloaded
with Mercurial.
The project comes with JavaScript tests which can be run from the command line as follows:
  $ java -jar JsTestDriver.jar --port 4224


This will start a server on http://localhost:4224
Open your favorite browser (we don't recommend IE as it is slow) at http://localhost:4224 and click the
“Capture This Browser” link.

From a new command line enter:
  $ java -jar JsTestDriver.jar --tests all


You should see something like this:
  $ java -jar JsTestDriver.jar --tests all
  ........
  Total 8 tests (Passed: 8; Fails: 0; Errors: 0) (10.00 ms)
    Chrome 4.0.202.0 MacIntel: Run 8 tests (Passed: 8; Fails: 0; Errors
  0) (10.00 ms)




OOPSLA 2009 Tutorial                               2                                     Miško Hevery
2 Understanding Manual Dependency Injection

2.1 Application Wiring Diagram
The application is a simple game of Tic-Tac-Toe as shown on the
right. The application is intentionally kept small for simplicity and
consists of these components.
   •   HTML (tic-tac-toe.html)
       ◦ #status: location of the status element.
       ◦ #board: location of the board game.
       ◦ #newGame: button reseting the game.
   •   Classes
       ◦ Board: Responsible for updating the DOM to show
         current state of the board.
       ◦ State: Internal representation of the board, which can
         determine a winner and reflects the DOM view of the
         board.
       ◦ Status: Updates the status DOM with the player turn
         and shows the winner.
       ◦ ManualDI: Bootstrap class which is responsible for wiring the application class together.
   •   Events
       ◦ Board Click: fired when the user clicks on the board game.
       ◦ New Game Click: fired when the user clicks on the “New Game Button.”

2.2 Understanding the Need for DI
A common misconception is that dynamic languages do not need Dependency Injection. The argument
is that in dynamic languages one can easily change the method definition at run time. Therefore no
method is untestable because all methods have seams where the normal flow of code execution can be
diverted for the purpose of test isolation through monkey-patching. While DI is very useful for testing,
it also aids the understanding of the code base. This benefit would be lost without DI. However, the
main fallacy of this argument stems from the fact that code is global constant, and monkey-patching the
code turns the global constants to mutable global state. While global constants don't present testability,
maintainability, or understandability problems, mutable global state presents problems in all previously
stated categories. It is true that while in static languages, such as Java, lack of DI spells death to
testability, lack of DI in dynamic languages still allows testability through monkey-patching. However,
it is not a best practice, and creates a problem of global state as stated above.




OOPSLA 2009 Tutorial                                 4                                     Miško Hevery
3 Designing Automated Dependency Injection Framework
The file src/ManualDI.js contains all of the wiring of the application. This is an error prone
process as it can lead to mistakes which are hard to detect because there are no automated tests.
The goal is to completely replace this file with automatic DI. To achieve automatic DI we need to solve
several issues as discussed in more detail next.

3.1 Replacing the Lost Information of Declared Types
The automatic Dependency Injection works by looking at a constructor of a class to determine the
parameter types, then recursively looking at those types. Dynamic Languages usually don't contain this
information and therefore we need a mechanism for declaring the missing information. To solve this
problem, we will declare a class constant containing the missing meta-data information for the
framework.
See scr/Board.js and notice the class constant inject
  Board = function (board, state) {
     this.board = board;
     this.nextPiece = "X";
     this.state = state;
  };

  Board.inject = {
     constructor:["#board", ":Status"],
     scope: "singleton",
     listen:[
       {source:"#newGame", event:”click”, call:'reset'},
       {source:"#board.box", event:”click”,
                              call:'addPiece', args:["@row", "@col"]}
     ]
  };


The inject meta-data contains information used to automatically construct the object graph. Notice
that the references are prefixed with special characters:
   •   “:” inject an object of a given type
   •   “#” inject a DOM element with a given id (this is a jQuery selector)
   •   “@” inject a property of a given object

3.2 Injecting Types
The most important ability for any Dependency Injection framework is to instantiate and inject
instances of a given type. We will use the following syntax to locate objects.
  var injector = new Injector();
  var board = injector.getInstance(“:State”);


The goal of this tutorial is to implement an Injector class which can read the meta-data information of
classes and use it to instantiate the objects.

OOPSLA 2009 Tutorial                                6                                     Miško Hevery
3.3 Injecting DOM Elements
In addition to injecting types, common in most static language DI frameworks, we would also like the
ability to inject DOM elements, a common need in JavaScript code, using the jQuery selector syntax.
Therefore, asking for #board is equivalent to jQuery(document).find(“#board”).

3.4 Injecting Events
DOM element listeners are also common in JavaScript, and therefore, the ability to inject listeners is
desired. Our meta-data contains the “listen” directive which specifies in declarative way the kind of
events the class should listen on.




OOPSLA 2009 Tutorial                                8                                      Miško Hevery
4 Implementing the Framework
The goal of the tutorial is to implement an automatic DI framework which can read the meta-data and
use it to instantiate our application. We want to change the current ManualDI.js class from:
  Main.prototype.bind = function() {
    var boardElement = this.doc.find("#board");
    var state = new State();
    var board = new Board(boardElement, state);
    var status = new Status(this.doc.find("#status"), state, function(){
        return board.nextPiece;
      });
    boardElement.find('.box').click(function(){
      var e = $(this);
      board.addPiece(e.attr('row'), e.attr('col'));
      status.update();
    });

       this.doc.find('#newGame').click(function(){
         board.reset();
         status.update();
       });
       board.reset();
  };


to an automatic wiring DI as shown below:

  Main.prototype.bind = function() {
     var injector = new Injector();
     var board = injector.getInstance(“:Board”);
     board.reset();
  };


The implementation will be done in the following way:
   •    All code will be test driven with unit tests and test first design

   •    First, we will implement the ability to instantiate pure objects such as State.js which will
        allow us to replace new State() with injector.getInstance(“:State”)

   •    Then, we will add the ability to inject jQuery selectors which will allow us to replace the
        complex instantiation of State with injector.getInstance(“:Status”)

   •    Finally, we will add the ability to inject listeners which will allow us to replace the whole
        manual DI with injector.getInstance(“:Board”) which is the root object.




OOPSLA 2009 Tutorial                                  10                                     Miško Hevery
5 Comparing the Resulting Wiring Code
When done with implementing the framework, we will discuss:
   •   The benefits of simplified code
   •   The different paths each of us took in the implementation
   •   The advantages and disadvantages of each of the implementations
   •   How we could further improve and grow the framework




OOPSLA 2009 Tutorial                              12                     Miško Hevery

More Related Content

PDF
Intro to asp.net mvc 4 with visual studio
PPTX
Learning C# iPad Programming
PPTX
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
PDF
I pad uicatalog_lesson02
PDF
<img src="../i/r_14.png" />
PDF
Tellurium At Rich Web Experience2009
PDF
Tellurium.A.New.Approach.For.Web.Testing
PDF
Learning selenium sample
Intro to asp.net mvc 4 with visual studio
Learning C# iPad Programming
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
I pad uicatalog_lesson02
<img src="../i/r_14.png" />
Tellurium At Rich Web Experience2009
Tellurium.A.New.Approach.For.Web.Testing
Learning selenium sample

What's hot (19)

PPT
Java for Mainframers
PPTX
Appium Mobile Testing: Nakov at BurgasConf - July 2021
ODP
Plug yourself in and your app will never be the same (2 hour edition)
PDF
J boss ide-tutorial
 
PDF
Interview question & Answers for 3+ years experienced in Selenium | LearningSlot
PDF
Interview Question & Answers for Selenium Freshers | LearningSlot
PDF
Continuous Integration and Code Coverage in Xcode
PPTX
Eclipse e4 on Java Forum Stuttgart 2010
PDF
Introduction to html5 game programming with ImpactJs
PDF
Unit testing and Android
PDF
Implementing auto complete using JQuery
PDF
Testing on Android
PPT
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
PPT
JsUnit
PDF
Custom JSF components
KEY
Accelerate your Lotus Domino Web Applications with Dojo and XPages
PDF
Learn How to Unit Test Your Android Application (with Robolectric)
PDF
Robotium Tutorial
PDF
Pic programming gettingstarted
Java for Mainframers
Appium Mobile Testing: Nakov at BurgasConf - July 2021
Plug yourself in and your app will never be the same (2 hour edition)
J boss ide-tutorial
 
Interview question & Answers for 3+ years experienced in Selenium | LearningSlot
Interview Question & Answers for Selenium Freshers | LearningSlot
Continuous Integration and Code Coverage in Xcode
Eclipse e4 on Java Forum Stuttgart 2010
Introduction to html5 game programming with ImpactJs
Unit testing and Android
Implementing auto complete using JQuery
Testing on Android
Writing and Testing JavaScript-heavy Web 2.0 apps with JSUnit
JsUnit
Custom JSF components
Accelerate your Lotus Domino Web Applications with Dojo and XPages
Learn How to Unit Test Your Android Application (with Robolectric)
Robotium Tutorial
Pic programming gettingstarted
Ad

Viewers also liked (20)

PDF
UNA PROPUESTA DE TRABAJO COLABORATIVO PARA EL ANÁLISIS REFLEXIVO DE LA PRÁCTI...
PDF
Diesel Maintenance
PDF
Biotecnologie per lo sviluppo internazionale - Mauro Giacca, ICGEB Trieste
PDF
20131019 digital collections - if you build them will anyone visit [library 2...
PPTX
Media pitch!
ODP
C:\Users\Alumne\Desktop\Xarxes1
PDF
Montevalle Park
PPT
From hear to there
PDF
BERLIN STATUEN storyboard
PDF
Uu 05 1952
PPT
New e-Science Edinburgh Late Edition
PPT
珊瑚的介紹
ODP
Animals africa
PDF
Social Media 101 Slides
PPT
The Future of Learning and Learning for the Future
PPTX
Asistencia simulacros
ODP
Tema 2. hardware
PPTX
пантоміми
PPT
Differential equations
PPTX
Spring portfolio
UNA PROPUESTA DE TRABAJO COLABORATIVO PARA EL ANÁLISIS REFLEXIVO DE LA PRÁCTI...
Diesel Maintenance
Biotecnologie per lo sviluppo internazionale - Mauro Giacca, ICGEB Trieste
20131019 digital collections - if you build them will anyone visit [library 2...
Media pitch!
C:\Users\Alumne\Desktop\Xarxes1
Montevalle Park
From hear to there
BERLIN STATUEN storyboard
Uu 05 1952
New e-Science Edinburgh Late Edition
珊瑚的介紹
Animals africa
Social Media 101 Slides
The Future of Learning and Learning for the Future
Asistencia simulacros
Tema 2. hardware
пантоміми
Differential equations
Spring portfolio
Ad

Similar to tut0000021-hevery (20)

PPTX
Testing basics for developers
PDF
Splash
PPT
Pragmatic Parallels: Java and JavaScript
PDF
AD114 - Don't be afraid of curly brackets reloaded - even more JavaScript for...
PDF
City search documentation
PDF
SpencerKellerResume
PPTX
DSL, Page Object and WebDriver – the path to reliable functional tests.pptx
PDF
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
KEY
Enterprise Strength Mobile JavaScript
PPTX
DSL, Page Object и WebDriver – путь к надежным функциональным тестам
PDF
Unit testing (eng)
PDF
Completely Test-Driven
PDF
MartinVanha
PDF
AD111 -- Harnessing the Power of Server-Side JavaScript and Other Advanced XP...
PDF
Ad111
DOC
Qtp training in hyderabad
PDF
Selenium Online Training.pdf
DOC
City search documentation
PPTX
Software testing 2012 - A Year in Review
PDF
Beginning java and flex migrating java, spring, hibernate, and maven develop...
Testing basics for developers
Splash
Pragmatic Parallels: Java and JavaScript
AD114 - Don't be afraid of curly brackets reloaded - even more JavaScript for...
City search documentation
SpencerKellerResume
DSL, Page Object and WebDriver – the path to reliable functional tests.pptx
BDD, ATDD, Page Objects: The Road to Sustainable Web Testing
Enterprise Strength Mobile JavaScript
DSL, Page Object и WebDriver – путь к надежным функциональным тестам
Unit testing (eng)
Completely Test-Driven
MartinVanha
AD111 -- Harnessing the Power of Server-Side JavaScript and Other Advanced XP...
Ad111
Qtp training in hyderabad
Selenium Online Training.pdf
City search documentation
Software testing 2012 - A Year in Review
Beginning java and flex migrating java, spring, hibernate, and maven develop...

More from tutorialsruby (20)

PDF
<img src="../i/r_14.png" />
PDF
TopStyle Help & <b>Tutorial</b>
PDF
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting <b>...</b>
PDF
<img src="../i/r_14.png" />
PDF
<img src="../i/r_14.png" />
PDF
Standardization and Knowledge Transfer – INS0
PDF
xhtml_basics
PDF
xhtml_basics
PDF
xhtml-documentation
PDF
xhtml-documentation
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
HowTo_CSS
PDF
HowTo_CSS
PDF
BloggingWithStyle_2008
PDF
BloggingWithStyle_2008
PDF
cascadingstylesheets
PDF
cascadingstylesheets
<img src="../i/r_14.png" />
TopStyle Help & <b>Tutorial</b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting <b>...</b>
<img src="../i/r_14.png" />
<img src="../i/r_14.png" />
Standardization and Knowledge Transfer – INS0
xhtml_basics
xhtml_basics
xhtml-documentation
xhtml-documentation
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
HowTo_CSS
HowTo_CSS
BloggingWithStyle_2008
BloggingWithStyle_2008
cascadingstylesheets
cascadingstylesheets

Recently uploaded (20)

PDF
A comparative study of natural language inference in Swahili using monolingua...
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
August Patch Tuesday
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PPTX
TLE Review Electricity (Electricity).pptx
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
Getting Started with Data Integration: FME Form 101
PPTX
Tartificialntelligence_presentation.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
A Presentation on Artificial Intelligence
PDF
project resource management chapter-09.pdf
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
A comparative study of natural language inference in Swahili using monolingua...
OMC Textile Division Presentation 2021.pptx
August Patch Tuesday
SOPHOS-XG Firewall Administrator PPT.pptx
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
DP Operators-handbook-extract for the Mautical Institute
TLE Review Electricity (Electricity).pptx
Hindi spoken digit analysis for native and non-native speakers
Getting Started with Data Integration: FME Form 101
Tartificialntelligence_presentation.pptx
Approach and Philosophy of On baking technology
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
Encapsulation theory and applications.pdf
Enhancing emotion recognition model for a student engagement use case through...
NewMind AI Weekly Chronicles - August'25-Week II
A Presentation on Artificial Intelligence
project resource management chapter-09.pdf
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...

tut0000021-hevery

  • 1. Table of Contents Table of Contents........................................................................................................................................ i Instructors Biographies.............................................................................................................................. ii Agenda...................................................................................................................................................... iii Objectives Of the Course.......................................................................................................................... iv 1Setting Up Environment...........................................................................................................................6 1.1Setting up Mercurial.........................................................................................................................6 1.2Setting up Your Favorite Text Editor or Eclipse...............................................................................6 1.3Getting the Source............................................................................................................................ 6 1.4Setting up Test Runner..................................................................................................................... 8 2Understanding Manual Dependency Injection.......................................................................................10 2.1Application wiring diagram............................................................................................................10 2.2Understanding the Need for DI...................................................................................................... 10 3Designing Automated Dependency Injection Framework..................................................................... 12 3.1Replacing the Lost Information Of Declared Types.......................................................................12 3.2Ability to Inject Types.................................................................................................................... 12 3.3Ability to Inject DOM Elements.................................................................................................... 14 3.4Ability to Inject Events...................................................................................................................14 4Implementing the Framework................................................................................................................ 16 5Comparing the Resulting Wiring Code.................................................................................................. 18 OOPSLA 2009 Tutorial i Miško Hevery
  • 2. Instructors Biographies Miško Hevery [email protected] Google, Inc. … works as an Agile Coach at Google where he is responsible for coaching Googlers to maintain the high level of automated testing culture. This allows Google to do frequent releases of its web applications with consistent high quality. Previously he worked at Adobe, Sun Microsystems, Intel, and Xerox (to name a few), where he became an expert in building web applications in web related technologies such as Java, JavaScript, Flex and ActionScript. He is very involved in Open Source community and an author of several open source projects. Recently his interest in Test-Driven- Development turned into Testability Explorer (http://code.google.com/p/testability-explorer) and JsTestDriver (http://code.google.com/p/js-test-driver) with which he hopes to change the testing culture of the open source community. OOPSLA 2009 Tutorial ii Miško Hevery
  • 3. Agenda 1. Setting up your environment 1. Setting up Mercurial 2. Setting up your favorite text editor or Eclipse 3. Setting up JsTestRunner 2. Getting the source 1. Checking out the source code 2. Running the code 3. Understanding manual Dependency Injection 1. Application wiring diagram 2. Understanding the need for DI 4. Designing automated Dependency Injection framework 1. Replacing the lost information of declared types 2. Injecting types 3. Injecting DOM elements 4. Injecting events 5. Implementing the framework 6. Cleaning up the bootstrap wiring code 7. Discussion of before and after code OOPSLA 2009 Tutorial iii Miško Hevery
  • 4. Objectives of the Course Dependency Injection is a good practice even in dynamic languages. Because many dynamic languages do not have type declarations, building an automatic DI framework presents its own set of challenges. Furthermore, many concepts, such as scopes that are often associated with threads, change their meaning in most dynamic languages which are single threaded. In this tutorial, we will build a simple automatic DI framework and solve many of the challenges which are associated with lack of declared types in such languages. • Understand the need for Dependency Injection ◦ Dynamic languages are not special and still need Dependency Injection • How to replace the lack of typing information in dynamic languages • Injection is not limited to injecting object instances ◦ Building our own domain specific language ◦ The obvious: Injecting types ◦ Thinking outside the box: Injecting DOM elements, and events • Dependency Injection simplifies the wiring of the application logic ◦ Comparing application bootstrap process before and after OOPSLA 2009 Tutorial iv Miško Hevery
  • 5. 1 Setting Up Environment Before the tutorial we recommend that you complete all of the following steps: 1.1 Setting up Mercurial The code for this project is located at: • http://bitbucket.org/misko/misko-hevery-oopsla-09 You will need to install Mercurial for your platform: • Home: http://mercurial.selenic.com/wiki/ • Download: http://mercurial.selenic.com/wiki/Download? action=show&redirect=BinaryPackages 1.2 Getting the Source After installing a copy of Mercurial you can download the source using the following command: $ hg clone https://[email protected]/misko/misko-hevery-oopsla-09/ 1.3 Setting up Your Favorite Text Editor or Eclipse You will need you favorite Text Editor for editing JavaScript, HTML, and CSS. We recommend Eclipse which you can download and install from the link bellow. We have already set up an Eclipse workspace for you in the Mercurial repository. • Download Eclipse: http://www.eclipse.org/downloads/ • Install JavaScript Editor: From Eclipse ◦ Help → Install New Software ◦ Select: Work With: Galileo ◦ Select: Web, XML, and Java EE Development ◦ Complete the installation by clicking the “Next” button • Install JsTestDriver for Eclipse ◦ Help → Install New Software ◦ Select: Work With: and enter: http://js-test-driver.googlecode.com/svn/update/ ◦ Select JsTestDriver ◦ Complete the installation by clicking the “Next” button • Import the DI project which you downloaded with Mercurial. OOPSLA 2009 Tutorial Miško Hevery
  • 6. 1.4 Setting up Test Runner NOTE: All commands need to be executed from the root of the source code which you downloaded with Mercurial. The project comes with JavaScript tests which can be run from the command line as follows: $ java -jar JsTestDriver.jar --port 4224 This will start a server on http://localhost:4224 Open your favorite browser (we don't recommend IE as it is slow) at http://localhost:4224 and click the “Capture This Browser” link. From a new command line enter: $ java -jar JsTestDriver.jar --tests all You should see something like this: $ java -jar JsTestDriver.jar --tests all ........ Total 8 tests (Passed: 8; Fails: 0; Errors: 0) (10.00 ms) Chrome 4.0.202.0 MacIntel: Run 8 tests (Passed: 8; Fails: 0; Errors 0) (10.00 ms) OOPSLA 2009 Tutorial 2 Miško Hevery
  • 7. 2 Understanding Manual Dependency Injection 2.1 Application Wiring Diagram The application is a simple game of Tic-Tac-Toe as shown on the right. The application is intentionally kept small for simplicity and consists of these components. • HTML (tic-tac-toe.html) ◦ #status: location of the status element. ◦ #board: location of the board game. ◦ #newGame: button reseting the game. • Classes ◦ Board: Responsible for updating the DOM to show current state of the board. ◦ State: Internal representation of the board, which can determine a winner and reflects the DOM view of the board. ◦ Status: Updates the status DOM with the player turn and shows the winner. ◦ ManualDI: Bootstrap class which is responsible for wiring the application class together. • Events ◦ Board Click: fired when the user clicks on the board game. ◦ New Game Click: fired when the user clicks on the “New Game Button.” 2.2 Understanding the Need for DI A common misconception is that dynamic languages do not need Dependency Injection. The argument is that in dynamic languages one can easily change the method definition at run time. Therefore no method is untestable because all methods have seams where the normal flow of code execution can be diverted for the purpose of test isolation through monkey-patching. While DI is very useful for testing, it also aids the understanding of the code base. This benefit would be lost without DI. However, the main fallacy of this argument stems from the fact that code is global constant, and monkey-patching the code turns the global constants to mutable global state. While global constants don't present testability, maintainability, or understandability problems, mutable global state presents problems in all previously stated categories. It is true that while in static languages, such as Java, lack of DI spells death to testability, lack of DI in dynamic languages still allows testability through monkey-patching. However, it is not a best practice, and creates a problem of global state as stated above. OOPSLA 2009 Tutorial 4 Miško Hevery
  • 8. 3 Designing Automated Dependency Injection Framework The file src/ManualDI.js contains all of the wiring of the application. This is an error prone process as it can lead to mistakes which are hard to detect because there are no automated tests. The goal is to completely replace this file with automatic DI. To achieve automatic DI we need to solve several issues as discussed in more detail next. 3.1 Replacing the Lost Information of Declared Types The automatic Dependency Injection works by looking at a constructor of a class to determine the parameter types, then recursively looking at those types. Dynamic Languages usually don't contain this information and therefore we need a mechanism for declaring the missing information. To solve this problem, we will declare a class constant containing the missing meta-data information for the framework. See scr/Board.js and notice the class constant inject Board = function (board, state) { this.board = board; this.nextPiece = "X"; this.state = state; }; Board.inject = { constructor:["#board", ":Status"], scope: "singleton", listen:[ {source:"#newGame", event:”click”, call:'reset'}, {source:"#board.box", event:”click”, call:'addPiece', args:["@row", "@col"]} ] }; The inject meta-data contains information used to automatically construct the object graph. Notice that the references are prefixed with special characters: • “:” inject an object of a given type • “#” inject a DOM element with a given id (this is a jQuery selector) • “@” inject a property of a given object 3.2 Injecting Types The most important ability for any Dependency Injection framework is to instantiate and inject instances of a given type. We will use the following syntax to locate objects. var injector = new Injector(); var board = injector.getInstance(“:State”); The goal of this tutorial is to implement an Injector class which can read the meta-data information of classes and use it to instantiate the objects. OOPSLA 2009 Tutorial 6 Miško Hevery
  • 9. 3.3 Injecting DOM Elements In addition to injecting types, common in most static language DI frameworks, we would also like the ability to inject DOM elements, a common need in JavaScript code, using the jQuery selector syntax. Therefore, asking for #board is equivalent to jQuery(document).find(“#board”). 3.4 Injecting Events DOM element listeners are also common in JavaScript, and therefore, the ability to inject listeners is desired. Our meta-data contains the “listen” directive which specifies in declarative way the kind of events the class should listen on. OOPSLA 2009 Tutorial 8 Miško Hevery
  • 10. 4 Implementing the Framework The goal of the tutorial is to implement an automatic DI framework which can read the meta-data and use it to instantiate our application. We want to change the current ManualDI.js class from: Main.prototype.bind = function() { var boardElement = this.doc.find("#board"); var state = new State(); var board = new Board(boardElement, state); var status = new Status(this.doc.find("#status"), state, function(){ return board.nextPiece; }); boardElement.find('.box').click(function(){ var e = $(this); board.addPiece(e.attr('row'), e.attr('col')); status.update(); }); this.doc.find('#newGame').click(function(){ board.reset(); status.update(); }); board.reset(); }; to an automatic wiring DI as shown below: Main.prototype.bind = function() { var injector = new Injector(); var board = injector.getInstance(“:Board”); board.reset(); }; The implementation will be done in the following way: • All code will be test driven with unit tests and test first design • First, we will implement the ability to instantiate pure objects such as State.js which will allow us to replace new State() with injector.getInstance(“:State”) • Then, we will add the ability to inject jQuery selectors which will allow us to replace the complex instantiation of State with injector.getInstance(“:Status”) • Finally, we will add the ability to inject listeners which will allow us to replace the whole manual DI with injector.getInstance(“:Board”) which is the root object. OOPSLA 2009 Tutorial 10 Miško Hevery
  • 11. 5 Comparing the Resulting Wiring Code When done with implementing the framework, we will discuss: • The benefits of simplified code • The different paths each of us took in the implementation • The advantages and disadvantages of each of the implementations • How we could further improve and grow the framework OOPSLA 2009 Tutorial 12 Miško Hevery