Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Date structures Immutable?

Tags:

c#

objective-c

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

like image 632
CStreel Avatar asked Dec 12 '12 00:12

CStreel


People also ask

Why is data structure immutable?

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.

Are dates immutable?

Date is not immutable, we need to make a defensive copy of java. util. Date field while returning a reference to this instance variable.

Why apps are built on immutable data structure?

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.

What does it mean for a data structure to be mutable?

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.


1 Answers

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.

like image 176
Erik Funkenbusch Avatar answered Sep 29 '22 11:09

Erik Funkenbusch