Encapsulate collections

来源:互联网 发布:同步看电视的软件 编辑:程序博客网 时间:2024/06/16 05:02

http://www.javapractices.com/topic/TopicAction.do?Id=173

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:

  • addThing(Thing)
  • removeThing(Thing)
  • getThings() - return an unmodifiable Collection
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;} 


0 0
原创粉丝点击