Defensive copying
Immutable objects
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 teamName, String headCoachName){ //..elided } public void addPlayer(Player player){ players.add(player); } public void removePlayer(Player player){ players.remove(player); } public Set<Player> getPlayers(){ return Collections.unmodifiableSet(players); } //..elided // PRIVATE private Set<Player> players = new LinkedHashSet<>(); private String teamName; private String headCoachName; }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 teamName, String headCoachName){ //..elided } public void setPlayers(Set<Player> players){ this.players = players; } public Set<Player> getPlayers(){ return players; } //..elided // PRIVATE private Set<Player> players; private String teamName; private String headCoachName; }