Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should methods return a new instance, rather than modify the instance itself?

Tags:

c++

oop

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?

like image 802
CRefice Avatar asked Sep 25 '26 05:09

CRefice


2 Answers

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);
like image 77
Sergey Kalinichenko Avatar answered Sep 26 '26 18:09

Sergey Kalinichenko


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.

like image 29
BitTickler Avatar answered Sep 26 '26 17:09

BitTickler