4 ms·
could someone take the time and explain to a moron like me why the mutability of moment is bad? i just don't get it. moment has always been my goto library for
by thrownaway954 6y ago
could someone take the time and explain to a moron like me why the mutability of moment is bad? i just don't get it. moment has always been my goto library for dealing with dates in javascript.
- fendy3002 6y agoDisclaimer: I too use moment in my daily project Example snippet (CMIIW, it's as I remembered): let date1 = moment("2020-01-01"); let date2 = date1.add(2, "days"); console.log(date1.format("YYYY-MM-DD")); // 2020-01-03 date2.add(2, "days"); console.log(date1.format("YYYY-MM-DD")); // 2020-01-05 Usually the date1.add operation won't change the date1 value, and any operation to date2 won't change date1, but it isn't. It's made worse because people like to return moment object outside function scope, so operation outside can modify the object inside and weird bugs happen. It's actually a manageable problem IF you know the behavior, and only using moment object reference inside scope, and using immutable objects as parameter / return, such as milliseconds timestamp and js date.
- perlgeek 6y agoOK, let me try. Most software has "reference types", like a customer. A customer is mutable; for example their name can change for a variety of reasons, their shipping address can change etc. And then there are "value types", like integers or strings. The integer 42 can never change to be any other value. If your customer lives in Rando Street no 42, and moves to Rando Street 41, you don't change the integer (value type) 42 to 41, you set `custtomer.address.house_number` to the new integer 41. If any other code referenced the number 42, it still has number 42 stored. Now, many people argue that a moment in time (like timestamp/datetime) is usually better modeled as a value type. If you have two references to one moment, you can rely on the fact that nobody else can modify that moment after the fact. This is usually safer, since it makes the case of accidentally over-shared objects a non-problem, though possibly a little bit less performant (since all "modifications" must create new copies).