Separate persistent and derivated fields [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
开发者_如何学Go Improve this questionwhat are the possibilities to separate persistent and derivated attributes of bean? And what's the best practice at your opinion? Assume simple example below where spentMoney
and numberOfDays
are persistent attributes and avrageSpendingPerDay
is derivated attribute. Thank you for your answer to this design question.
class Person implements Serializable {
private BigDecimal spentMoney;
private int numberOfDays;
public Person() {
}
public BigDecimal getSpentMoney() {
return spentMoney;
}
public void setSpentMoney(BigDecimal spentMoney) {
this.spentMoney = spentMoney;
}
public int getNumberOfDays() {
return numberOfDays;
}
public void setNumberOfDays(int numberOfDays) {
this.numberOfDays = numberOfDays;
}
public BigDecimal getAvrageSpendingPerDay() {
return spentMoney.divide(new BigDecimal(numberOfDays), 2, RoundingMode.HALF_EVEN);
}
}
You don't need to separate them. That's the whole point of encapsulation. The caller knows there is a getAvrageSpendingPerDay
method, but doesn't care if it's implemented through a persistent attribute or not.
You might change your mind and keep the same public methods, but recompute the average and store it inside a field each time setSpentMoney
or setNumberOfDays
is called, without changing anything in the rest of the code. That's why using getters is better than accessing public fields directly.
I don't think you need to think about a design choice only with the information that some of the attributes are persistent and others are derived. You have already taken care of the important thing i.e. not having a member-field for derived attributes.
I think you're a tad confused... serialization persists the FIELDS not the methods... and you don't have a avrageSpendingPerDay
FIELD in your example.
If you where (just say) to make spentMoney and numberOfDays final (i.e. set only by the contructors, and immutable thereafter) then you COULD cache the result of your getAverageSpendingPerDay method in a field (upon first request)... and then you'd just mark your "cache field" _averageSpendingPerDay as transient
.
Cheers. Keith.
精彩评论