DEV Community

loading...
Cover image for What Is Dependency Injection?

What Is Dependency Injection?

Elle Hallal πŸ‘©πŸ½β€πŸ’»
Software Engineer. Leadership Team Member & Mentor at Coding Black Females πŸ‘©πŸ½β€πŸ’»
Originally published at ellehallal.dev on ・2 min read

Originally posted at ellehallal.devπŸ‘©πŸ½β€πŸ’»


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.

class Game {
  constructor() {
    this.board = new Board();
    this.player1 = new HumanPlayer();
    this.player2 = new HumanPlayer();
  }
}

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.

class Game {
  constructor(board, player1, player2) {
    this.board = board;
    this.player1 = player1;
    this.player2 = player2;
  }
}

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


const board = new Board(['o', 'x', 'x', 'x', 'o', 'o', 'o', 'x', 'x'])
const humanPlayer = new HumanPlayer();
const computerPlayer = new ComputerPlayer();
const 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!


Discussion (0)