
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();}}
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;}}
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)
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)
For further actions, you may consider blocking this person and/orreporting abuse