Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

See the examples below:

function map_cloning(obj,fn){
    result = {};
    for (var key in obj)
        result[key] = fn(obj[key]);
    return result;
};
function map_modifying(obj,fn){
    for (var key in obj) 
        obj[key] = fn(obj[key]);
    return obj;
};

function sum_cloning(vector1,vector2){
    return [vector1[0] + vector1[1], vector2[0] + vector2[1]];
};
function sum_modifying(vector1,vector2){
    vector1.x += vector2.x;
    vector1.y += vector2.x;
    return vector1;
};

function tail_cloning(obj){
    return obj.slice(1);
};
function tail_modifying(obj){
    obj.splice(0,1);
    return obj;
};

Often you have to chose between cloning or not an object before making a computation. Which is best?

share|improve this question

2 Answers

I suggest cloning. If it was possible (like in Java), I'd even suggest making your objects immutable...

Why do I suggest cloning? Consider being after a busy Friday, with business users ranting all day on some totally unimportant feature, and you see this code fragment all of a sudden, having a, b and c variables:

b=sum_modifying(a,b);
 //some other code here
a=sum_modifying(c,a);
 //some other code here
b=sum_modifying(c,a);

Will you be able to track back what's going on? I woudn't, for sure...

Even this is a tough situation, but at least, the value of the variables change only with the assignment.

b=sum_cloning(a,b);
 //some other code here
a=sum_cloning(c,a);
 //some other code here
b=sum_cloning(c,a);

However, I'd suggest a third alternative: add functions to the objects themselves, to enable schemes like this:

result = a.add(b);

I'd find this the most readable of these. (I stole the idea mainly from Java's BigDecimal.)

share|improve this answer

Definitely default to cloning an object and leaving the original untouched. If the calling code wants to replace the original object, it can assign the function result to that variable. This way it's much clearer what you're doing at each step, and it's much harder to screw something up. It's also in keeping with the mentality of having functions that process input and return output, rather than having functions that perform "magic" on state outside of themselves.

I find Underscore/Lodash's _.clone very useful for this, I use it all the time. In fact, I use it almost to the exclusion of new and Object.create.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.