Let's say we have classes something like this:
public class Item1{
public Guid Id {get; set;}
public string Name {get; set;}
public decimal Price {get; set;}
public int Quantity {get; set;}
}
And few more, which has additional or different fields, other have lists as properties.
And those classes are being serialized into Xml string and placed as property of another class, which will be saved in database.
public class Record{
public Guid Id {get; set;}
public DateTime CreatedOn {get; set;}
public string SerializedItem {get; set;}
}
When we need, we pull out record and deserialize into class Item1
, Item2
or whatever. Everything is nice and fine.
But one day we decide, that we need additional property Discount
. If Price * Quantity > 1000
discount would be 10
for that item, if greater than 5000 discount 20 and so on. And we would use those classes for showing in a grid(simple list), generating reports and probably like a variable in classes ( e.g. if discount is greater than 20 that item would could not get a free shipping or something). In order not to duplicate Discount
calculation, we decide to have additional property in our class Item1
like public decimal Discount {get; set;}
, which is calculated while inserting this new item.
So here's the problem we see: when deserializing old items they would not have that property, so deserializer would give a default values like null
, 0
, false
depending on property type. However we want old items to have a Discount
value calculated according to the logic that new items Discount
is calculated.
So how to achieve that efficiently? Would it be wise to to have a method that would recalculate that discount(note that there might be a couple thousands of item, and logic would be more complicated) before giving these items to grid, reports and somewhere else? Or is it more efficient to have a script which would loop through all records and would calculate discount, and run it once after upgrading to new version?
Any insights and suggestion are appreciated. And please let me know or edit if title and tags are inappropriate or too vague.
loadRecord() { ...; if (discount == null) {calculateDiscount();} }
IfcalculateDiscount()
is scattered all over the place / embedded in some lengthy function, gather it up in one place