Should I replace a simple setter
public void setCategories(Set<String> categories)
{
this.categories = categories;
}
with something like this:
public void setCategories(Collection<String> categories)
{
this.categories.clear();
if (categories != null)
{
this.categories.addAll(categories);
}
}
so object’s attribute categories won’t be further modifiable through passed parameter reference as it could be:
Set<String> categories = new TreeSet<String>();
categories.add("cityguide");
categories.add("other");
Document document = new Document("http://unique-address.com");
document.setCategories(categories);
System.out.println(categories); //outputs [cityguide, other]
System.out.println(document.getCategories()); //outputs [cityguide, other]
document.setCategories(categories);
categories.add("traveling");
System.out.println(categories); //outputs [cityguide, other, traveling]
System.out.println(document.getCategories()); //outputs [cityguide, other, traveling]
yes, yes you should
another option is also making a new set for the field in the setter but your solution is better as it avoid the (unnecessary) allocation
or remove and add each category in a loop
so you won’t have to duplicate any triggers for removing and/or or adding a category