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)
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.