Mutability in object-oriented programming

What is Mutability?

Mutability in object-oriented programming is the concept of how a data type handles change. Do we need to copy the value, can we share the value, can the value be altered once created? These are really fundamental and important questions to answer when it comes to integrity and reliability when it comes to our application.

The principle of Mutability in object-oriented programming states that if an object can be changed then it is mutable. However, if it cannot be changed with creating a completely new object, then the object is considered immutable. Please keep in mind that how this is applied will vary from language to language. For example, in Java, everything (except for strings) is mutable and in Python lists, sets and dictionaries are mutable.

Immutability, like the statically typed vs interpreted principle, is not black and white and there exist some gray areas. For example, the use of const in C++, final in Java.

Why do we need Mutability?

The short answer is, thread safety. Modern languages tend towards immutable data types because it makes multi threading easier. An immutable value can be shared between threads without the need for locking or copying.

If a type is immutable, functions and container objects can share the instance which has already been saved within memory, improving concurrent programming and thread safe operations. You don’t risk breaking code by accidentally sharing between functions and contained objects.

Additionally, imagine the cost in CPU cycles if every write had to duplicate the buffer. That would get pretty gross pretty fast.

An Example of the Principle of Mutability in Python

##An example of the mutability of the int data type
>>> i = [1,2,3]
>>> print(i)
>>> print(id(i))
>>> i[0] 
>>> i[0] = 7
>>> print(id(i))
>>> print(i)

output:
907711259336
[1, 2, 3]
907711259336
[7, 2, 3]
##An example of the immutability of the string data type
>>> s = "abc"
>>> print(id(s))
>>> print(s[0])
>>> s[0] = "o"
>>> s = "xyz"
>>> print(id(s))
>>> s += "uvw"
>>> print(id(s))

output: 
  s[0] = "o"
TypeError: 'str' object does not support item assignment

I hope this answered your question. Happy coding!