is it a bad practice modifing an object passed as an argument inside a method?
what is the difference between doSomething1 and doSomething2? the both does the same but in a different way. which are appropriate and why is that?
class Foo {
constructor () {
this.bar = { aaa: 123, bbb: 456 }
this.doSomething1(this.bar)
this.doSomething2()
}
doSomething1(arg) { arg.aaa = 10 },
doSomething2() {
this.bar.bbb = 0
}
}
the code itself is not practical but just a sample code.
That's the difference between a function and a method. A method, which is a function defined on an object, knows all the properties of the object and is allowed to modified them (also known as mutate or change the state). doSomething2
is a method of Foo
class. Hence it should have the right or privilege to mutate any of the properties of an instance of Foo
.
doSomething1
on the other hand is a function masquerading as a method. It has no right to modify the argument it receives and so shouldn't. If it really must, then create a new copy with the updated property instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With