Suppose I have a Vector3 class, that contains a normalize() method. Should that method return a new Vector3, or modify the Vector3 instance it is called on (therefore returning a reference to itself (Vector3&)?) What are some instances where one would be preferred over the other? What about performance?
The answer depends on the design of your class.
For mutable classes rotate should rotate the vector itself. This is viewed as somewhat more efficient, and in case of large objects it lets you avoid copying large volumes of data when vectors have many items in them.
Immutable classes, on the other hand, must return only new objects, because they cannot be mutated themselves. This adds some overhead, but it has a lot of pluses, especially when objects must be used concurrently.
A common naming convention is to use a verb for mutating operations, as in
myVector.rotate(angle);
myVector.scale(factor);
while operations that return new objects should be named with past participles, as in
auto newVector = myVector.rotated(angle).scaled(factor);
Competing goals: Correctness vs Performance (sometimes).
If you use immutable types, you have it easier to write correct (parallel) programs. If you use mutable types, you sometimes have a certain performance benefit which might well be lost once you try to go parallel. Then there is the 80/20 rules. 80% of the code need not be optimized. So why use mutable types by default?
First go immutable, then see if it has enough performance, then optimize, if not.
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