Simberon Design Minute
 

Modify or Copy

You're writing a library for a 3D graphics application and you need to create a class for a 3D point. When you get to the method to add two 3D points together you realize that you have a decision to make. Do you modify the existing point with the total or do you return a new point for the answer leaving the originals untouched? Both techniques will work. My concern here would be fragility. If some other object is holding onto the points and you go and modify one of them, it appears to the other object that you changed the value under its feet. It's likely that the program would experience a bug because of the side effect. Making a copy for the answer has no side effects. There are cases, however, where performance concerns dictate that the creation and garbage collection of the new object is too expensive. Measure the performance both ways first. If creating a new object is a problem, you may need to compromise your design in order to make it work at the risk of encountering more bugs and more difficult coding as a result.

Download