I've searched for some project patterns for mapping what I called "derived properties". I'm posting some solutions and the problems of each of them and I want the opinion of everybody who had these same problems.
The Problem:
Code:
public class Cart {
double itemsValue;
double freight;
double totalValue; \\items value + freight
List<CarteItem> itemList;
}
public class CartItem {
double itemValue;
}
The question is: How to map the totalValue and the itemsValue properties?
The Solutions:1 - Update the total value and itemsValue for all changes in cart object.
Code:
//<property name="itemsValue" access="field" />
setItemsValue(double v) {
itemsValue = v;
recalculate();
}
recalculate() {
totalValue = itemsValue + freight;
}
Problem: Imagine a property that is derived from the value of 15 other properties ... Each set method should've to be modified to set the attribute and recalculate the values.
2 - Map the consolidated attributes without the existence of the corresponding fields. Ex:
Code:
getItemsValue() {
double v = 0;
for (CartItem item:itemList) {
v+=item.itemValue;
}
return v;
}
setItemsValue(double v) {}
getTotalValue() { return itemsValue + freight; }
setTotalVallue(double v) { }
Problem: Problem with dirty check. Depending on the database the value stored by hibernate to do the check is deferent from the value calculated causing a database update even without any change. Another problem is the need for initialization of all items to get the total items value.
[/code]