Encapsulate collections

In general, Collections are not immutable objects. As such, one must often exercise care that collection fields are not unintentionally exposed to the caller.

One technique is to define a set of related methods which prevent the caller from directly using the underlying collection, such as:

Example 1

import java.util.*;

public final class SoccerTeam {

  public SoccerTeam(String aTeamName, String aHeadCoachName){
    //..elided
  }

  public void addPlayer(Player aPlayer){
    fPlayers.add(aPlayer);
  }

  public void removePlayer(Player aPlayer){
    fPlayers.remove(aPlayer);
  }

  public Set<Player> getPlayers(){
    return Collections.unmodifiableSet(fPlayers);
  }

  //..elided

  // PRIVATE 
  private Set<Player> fPlayers = new LinkedHashSet<>();
  private String fTeamName;
  private String fHeadCoachName;
} 

Example 2

BaseballTeam is an example of exposing the collection directly to the caller. This is not necessarily an incorrect design, but it's riskier, since the contents of the collection can be directly changed by both BaseballTeam and its caller:


import java.util.*;

public final class BaseballTeam {

  public BaseballTeam(String aTeamName, String aHeadCoachName){
    //..elided
  }

  public void setPlayers(Set<Player> aPlayers){
    fPlayers = aPlayers;
  }

  public Set<Player> getPlayers(){
    return fPlayers;
  }

  //..elided

  // PRIVATE
  private Set<Player> fPlayers;
  private String fTeamName;
  private String fHeadCoachName;
} 



See Also :
Defensive copying
Immutable objects
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -