I know there is no right and wrong answer here, I'm just looking for other opinions on who should handle (削除) immutability (削除ここまで), dependency inversion and decoupling.
Example 1: Here each function caller has the responsibility to pass a new object, let the function handle the changes and then return the response. The function implementer doesn't care about anything else other than the function contents.
function doSomething (something) {
something.param = 1 // user input
return {
data: something
}
}
// Caller 1
const response = doSomething(JSON.parse(JSON.stringify(data)))
// Caller 2
const response = doSomething(JSON.parse(JSON.stringify(data)))
Example 2: Here the function implementer has the responsibility to clone the new object, do the changes and then return the response.
function doSomething (something) {
const tmpSomething = JSON.parse(JSON.stringify(something))
tmpSomething.param = 1 // user input
return {
data: tmpSomething
}
}
// Caller 1
const response = doSomething(data)
// Caller 2
const response = doSomething(data)
1 Answer 1
if you return an object of MyType
, I (personally) would expect it to be a new object
I guess it's because I would expect to modify the parameter by using a ref call.
Also it would look weird:
var obj = new MyType();
var modifiedobj = EditSomething(obj);
If i see this code, i do not expect obj
and modifiedObj
to be the same, that's just confusing.
-
1@DavidArno thx, I missed that. I've tried to adapt my answer to work for javascript. Though this question is not necessarily tied to a specific language.HankTheTank– HankTheTank2019年03月13日 11:47:52 +00:00Commented Mar 13, 2019 at 11:47
-
You are right it isn't necessarily for javascript, it could apply to any other by ref language.Stefanos Chrs– Stefanos Chrs2019年03月13日 13:26:17 +00:00Commented Mar 13, 2019 at 13:26
-
it might be confusing, but it's not uncommonEwan– Ewan2019年03月13日 15:46:33 +00:00Commented Mar 13, 2019 at 15:46
Explore related questions
See similar questions with these tags.
something
. So since only example 2 achieves immutability (ignoring the fact thattmpSomething
is mutated before being returned), then that has to be the answer to your question.