I would like to know in what scenarios you use encapsulation. The purpose of this question is collaborative. So feel free to share your own experience when the subject is encapsulation.
Some scenarios:
Calculated property
public class Order {
private List<ListItem> listItems = new ArrayList<ListItem>();
public double getTotal() {
double total = 0;
for(ListItem listItem: listItems)
total += listItem.getQuantity() * listItem.getPropduct().getPrice();
return total;
}
}
Self-validating domain objects
public class Person {
private String name;
public void setName(String name) {
if(StringUtils.isBlank(name)) {
throw new NotEmptyException("name", name);
}
this.name = name;
}
}
Makes use of other kind of classes for some special behavior
public class Person {
private MutableInt id = new MutableInt();
/**
* Integer itself is immutable
*/
public Integer getId() {
retur id.intValue();
}
}
Conversion
public class Person {
public String enabled;
public boolean isEnabled() {
return "Y".equals(enabled);
}
}