Setter methods set fields in each others class

Viewed 40

I have two classes, Player and Team. A player has a team field, and a team has a playerList field, containing the players on that team. When a player joins a team, the player's team field should be set to that team, and the team's playerList should add the player object joining. This is what I have so far, but is this not very recursive? How can I solve this problem? Example code is provided below.


public class Team {

   private ArrayList<Player> playerList;
   
   public void addPlayer(Player player){
      playerList.add(player);
      player.joinTeam(this);
   }

}

public class Player {
   
   private Team team;
   
   public void joinTeam(Team team) {
      this.team = team;
      team.addPlayer(this)
   }

}


2 Answers

In principle, you should only really have one function for a specific type of action. If you want to add a Player to a Team, something like

public class Team {

   private ArrayList<Player> playerList;
   
   public void addPlayer(Player player) {
      playerList.add(player);
      player.setTeam(this);
   }
}

public class Player {
   
   private Team team;
   
   public void setTeam(Team team) {
      this.team = team;
   }
}

would be better suited for your task. You only call one method (addPlayer) and both actions you want to have happen, will happen.

Well, to make your code work, you should just remove team.addPlayer(this) from the method joinTeam(). But now you are just setting a value to your attribute, so it should be a setTeam().

public class Team {

   private ArrayList<Player> playerList;
   
   public void addPlayer(Player player){
      playerList.add(player);
      player.joinTeam(this);
   }

}

public class Player {
   
   private Team team;
   
   public void setTeam(Team team) {
      this.team = team;
   }

}
Related