views:

56

answers:

2

Just a quickie to get a feel for the community in general's preference: When working with objects like Vectors (mathematical, not STL) and Matrices do you prefer a library that:

A) Doesn't alter the objects but returns copies instead:

Vec2 Vec2::Add(float x, float y) {
    return Vec2(this.x + x, this.y + y);
}

B) Alters the objects and returns references:

Vec2& Vec2::Add(float x, float y) {
    this.x += x;
    this.y += y;
    return (*this);
}

I can see some pros and cons to both, but the big thing for me is that method B would be more efficient.

So, opinions?

+1  A: 

The depends on the language and how it will integrate with the dominant frameworks.

However, in general, I prefer version A, IF you're only working with small vectors and matrices. For example, if this is a graphics library, and you're working with 2-4 vectors and 3x3 and 4x4 matrices, I prefer making them immutable, and not necessarily dealing with references. (This is providing you're using a language where the construction cost isn't going to kill your performance.)

If you're dealing with large matrices, I tend to prefer references, since the overhead of copying and construction is too great.

Reed Copsey
A: 

for value objects, its often better to return a new value.

and there may or may not be much difference in performance

Keith Nicholas