DEV Community

Cover image for What Is Dependency Injection?
Elle Hallal πŸ‘©πŸ½β€πŸ’»
Elle Hallal πŸ‘©πŸ½β€πŸ’»

Posted on β€’ Originally published at ellehallal.dev on

1

What Is Dependency Injection?

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
  }
}

Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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!


Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here β†’

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay