Reputation: 136
I dont think its pretty to use this
as a class parameter because there could occur errors if the order of initialization of the objects is not right.
Whats best practise to avoid this?
Example:
public class Game{
private Player p1, p2, currentPlayer;
private Board board;
Game() {
board = new Board(this);
}
private boolean hasFieldsToBeClicked() {
return board.checkFieldsToBeClicked();
}
Upvotes: 2
Views: 106
Reputation: 5183
1) What about a builder, which creates the game and the board at first without the other. Then the builder can set the Board in the Game and the Game in the Board.
2) It seems the Board is an inherent part of the Game.
Upvotes: 0
Reputation: 140525
From a design point of view: just don't do it here!
Meaning: a Board
represents a board. Does your chess board know about the game you are currently having, or not?
In other words: passing this
can be ok, but as you pointed out, it can also be a problem. Thus the best practice is: only pass this
if you have good reasons to. Especially when it occurs within the constructor and this
is still in the process of being initialized.
Enabling a chess board to know about an ongoing game isn't really a good reason.
Keep in mind: your classes/objects should model the real world. Only establish relations that are meaningful!
So the real answer here would be to look into why your Board class needs to know about the Game class, to then get rid of that dependency.
Upvotes: 6