I am wondering as to why Date structures & objects, like C#'s DateTime & Obj-C's NSDate have been made immutable.
Im looking for the reasoning behind this design and the benefits of making this information immutable, not just "because they can"
UPDATE: It seems as though there was a similar question with a fantastic answer to mine but specifically targeting Java, it can be found here: Why do we need immutable class?
That in combination with the answer to my question has been very informative
Immutable data structures provides referential transparency which makes it easier to reason about our program locally. Another way to think about it is that every time we execute a pure (referentially transparent) function with the same input, we get the same output.
Date is not immutable, we need to make a defensive copy of java. util. Date field while returning a reference to this instance variable.
Besides reduced memory usage, immutability allows you to optimize your application by making use of reference- and value equality. This makes it really easy to see if anything has changed.
Mutable data refers to a database structure in which data can be changed. Any data changes made simply overwrite and replace the previous record. This means that previous iterations of data are lost unless there is a system of back-ups and transaction logs that track changes.
Immutability makes a lot of things easier. If you don't have to worry that something can change underneath you, then there is a lot of guard code you don't have to write. There's a lot of assumptions you don't have to make. There's a lot of possibilities for things to NOT go wrong.
It's common for strings, dates, and other kinds of common objects to be immutable in modern languages because it simplifies the compiler, the framework, and means the compiler is free to make assumptions when doing optimization.
The gist is that, for a small price (having to create a new object if you want to change the value) you get a lot of real performance, stability, and reliability.
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