DEV Community

Discussion on: Should function arguments be reassignable or mutable?

Collapse
 
rhymes profile image
rhymes • Edited

I agree that function arguments should be immutable, it's the safer option but it's true there's no definitive consensus on this.

Languages that have objects and "pass by reference" allow you to modify a given object as argument and also with that they occupy less memory.

If you have a complex object in memory you can make a function setTheseRelatedFields(object) which might or not return anything but which operates on the given object by address instead of making a copy for the function.

The other side of coin is that sometimes it leads to unexpected consequences (side effects).

I usually have a "semi functional" approach even in languages that are not functional, the code tends to be easier to test and read.

So, if I were to design functions I would make the arguments read only BUT with an option to mutate the passed variable (which is indeed a label standing in for something, be it an integer or a hash).

If the argument is a "simple" value reassign it leads to an error, if the argument is an array changing one of the items leads to an error, the same for hashes and so on.

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

I wonder how much the lack of consensus rests on history though. For languages in the C family it'd be kind of shocking if a new one had differnet semantics.

But I don't want history holding me back. It does seems the consensus on a "safe default" would be immutable and not-rebindable. It's only a default of course, and there must be a way to mark arguments as mutable.