What Is Dependency Injection?


2 min read

This is a quick blog on how I've used dependency injection to improve the design of my JavaScript Tic Tac Toe game.

In the example below, when the Game class is initialised, instances of the Board and Player classes are also created.

1class Game {
2 constructor() {
3 this.board = new Board();
4 this.player1 = new HumanPlayer();
5 this.player2 = new HumanPlayer();
6 }
7}

If we wanted to add a new type of player (ComputerPlayer) as an option in our game, the above code would make it difficult to do so. This is because the player types are "hardcoded" in the Game's constructor'. This is where dependency injection comes in.


What Is It?

In software engineering, dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. — Wikipedia


Let's apply this to our example. Instead of "hard coding" the classes to be initialised inside of Game's constructor, we can pass them in.

1class Game {
2 constructor(board, player1, player2) {
3 this.board = board;
4 this.player1 = player1;
5 this.player2 = player2;
6 }
7}

When we initialise a new instance of Game, we can pass in our arguments.

1const board = new Board(['o', 'x', 'x', 'x', 'o', 'o', 'o', 'x', 'x'])
2const humanPlayer = new HumanPlayer();
3const computerPlayer = new ComputerPlayer();
4const game = new Game(board, humanPlayer, computerPlayer)

As a result, this improves the flexibility of which dependents we can use with Game. For example, now we can initialise the class with two human players, or two computer players, or one of each!


Previous post:
Creating A Hangman Game With Ruby
Next post:
Testing User Input With Rspec

Discussion