Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for What Is Dependency Injection?
Elle Hallal 👩🏽‍💻
Elle Hallal 👩🏽‍💻

Posted on • Originally published atellehallal.dev on

     

What Is Dependency Injection?

Originally posted atellehallal.dev👩🏽‍💻


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

In the example below, when theGame class is initialised, instances of theBoard andPlayer classes are also created.

classGame{constructor(){this.board=newBoard();this.player1=newHumanPlayer();this.player2=newHumanPlayer();}}
Enter fullscreen modeExit 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 theGame'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 ofGame's constructor, we can pass them in.

classGame{constructor(board,player1,player2){this.board=board;this.player1=player1;this.player2=player2;}}
Enter fullscreen modeExit fullscreen mode

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

constboard=newBoard(['o','x','x','x','o','o','o','x','x'])consthumanPlayer=newHumanPlayer();constcomputerPlayer=newComputerPlayer();constgame=newGame(board,humanPlayer,computerPlayer)
Enter fullscreen modeExit fullscreen mode

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


Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Senior Software Engineer. Leadership Team Member & Mentor at Coding Black Females 👩🏽‍💻
  • Location
    London, UK
  • Work
    Senior Software Engineer at 8th Light
  • Joined

More fromElle Hallal 👩🏽‍💻

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp