1

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)
  • 4
    Your first example isn't using immutability as you are modifying something. So since only example 2 achieves immutability (ignoring the fact that tmpSomething is mutated before being returned), then that has to be the answer to your question. – David Arno Mar 13 at 11:22
  • In the #1 the function also modifies a new object – Stefanos Chrs Mar 13 at 13:30
  • 4
    The function modifies the object passed to it in #1. The only way you can claim "function also modifies a new object" is if you only ever pass it a new object. That is not, in any way, immutability. Sorry. – David Arno Mar 13 at 13:46
  • 1
    Then you need to update your question to clarify this as this has nothing to do with immutability and everything to do with dependency inversion and decoupling. – David Arno Mar 13 at 14:16
  • 2
    surely neither. The object itself should be immutable or not. – Ewan Mar 13 at 15:33
4

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 Mar 13 at 11:47
  • You are right it isn't necessarily for javascript, it could apply to any other by ref language. – Stefanos Chrs Mar 13 at 13:26
  • it might be confusing, but it's not uncommon – Ewan Mar 13 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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