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 :
- addThing(Thing)
- removeThing(Thing)
- getThings() - return an unmodifiable Collection
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<Player>(); 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 is 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 :
Would you use this technique?
Add your comment to this Topic :
|