Can you suggest me a way that would prevent me from such a case when I am working with reference types?
var someCost = new Cost( Price: new Price(1000, "USD")
, CostType: "Type-A") ;
var candyCost = new Cost();
// Initialize candyCost.Price
candyCost.Price = someCost.Price; //Now candyCost Price is referencing
// price of someCost;
// (.......)
// Some logic and code here
//and I forgot that I was referencing to someCost object's price object
//and I do stupid mistake:
candyCost.Price.Value = 5000; //Now I believe I have updated candyCost price
//but I have also updated someCost!!
Rest of the story is about debugging to find out why someCost’s Price is updated.
I wanted to simplify the problem with this example. I hope if you get my meaning.
Question: Can you recommend me a way to secure myself from repeating such a mistake? any design patterns when it comes to updating values that are on reference types.
Your
Priceobject should be immutable – this will force you to assign a newPriceobject instead of changing the price of an existing one, hence avoiding the side effect.