Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I secure myself from updating another object over current object by mistake?

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.

like image 372
pencilCake Avatar asked Dec 16 '22 15:12

pencilCake


2 Answers

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.

like image 111
BrokenGlass Avatar answered Feb 02 '23 00:02

BrokenGlass


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)

like image 33
Andreas Dolk Avatar answered Feb 01 '23 22:02

Andreas Dolk