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 Price
object should be immutable - this will force you to assign a new Price
object instead of changing the price of an existing one, hence avoiding the side effect.
Depends on what you want to achieve with this line:
candyCost.Price = someCost.Price;
Do you want to say, that candyCost
and someCost
have the same price at this moment or that they always have the same price?
If you just want to initialize candyCost.Price
with a value that is equal to someCost.Prize
, than you should clone the Price
instance:
candyCost.Price = new Price(someCost.Price); // copy constructor pattern inside
(of course you have to implement the constructor)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With