Cases for mutability

Whenever we require to change an immutable object, we will need to create a new, modified copy of it. This might not be costly and tedious for small and simple objects but will be in cases where we have large or complex objects with lots of properties and operations.

Also, changing an existing object is simpler and much more intuitive than creating a new, modified copy of it for objects with a distinct identity, for instance, a profile of a user. We may want to maintain a single object of a user's profile and modify it when necessary. This might not be a great example as it is hard to see the performance penalty for this case but the speed of execution can be a very important differentiator for some types of applications such as games. As an example, representing our game characters with mutable objects may make our game run faster than an alternative implementation where we will need to create a new, modified copy of the game character whenever we need to change it.

Furthermore, our real-world perception is inevitably based on the concept of mutable objects. We deal with all objects around us in our real life. These objects are identical most of the time and we change some of their characteristics if required.

For instance, we paint a wall in our home instead of replacing the whole wall. We perceive the wall as the same object with a modified property, in this case, color. The wall's identity is maintained while its state changes when we paint it.

Therefore, whenever we model a real-world domain to represent real-world objects in our applications, it is inevitably easier to perceive and implement the domain model using mutable objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset