Chapter 9. Importance of Immutability

In object-oriented and functional programming, immutable objects are objects whose state cannot be changed or altered after they are initiated. Therefore, a mutable object stays the same until the end of its life cycle, when it is deinitialized. In contrast, a mutable object can be altered countless times by other objects after it is initiated.

Immutable objects improve readability and runtime efficiency and using them simplifies our applications.

This chapter will cover the concept of immutability by discussing the following topics with coding examples:

  • Immutability
  • The benefits of immutability
  • Cases for mutability
  • An example with approach comparisons
    • Side-effects and unintended consequences
    • Testability
  • Copy constructors
  • Lenses

Immutability

An immutable object is an object whose state cannot be modified after it is initiated. This quality of immutable objects is essential in multithreaded applications because it allows a thread to act on the data represented by immutable objects without worrying about changes from other threads.

An object is considered immutable if the object itself, and in fact all of its properties, are immutable. In some cases, an object is considered immutable even if some of its internal properties change but the object's state appears to be immutable from an external point of view. For instance, an object that uses the memoization technique to cache the results of resource-greedy calculations can be considered as an immutable object.

Immutable objects have the following features:

  • They are simple to construct, test, and use
  • They are simple to understand and reason about
  • They are inherently thread-safe and have no synchronization issues
  • They do not require a copy constructor
  • They always have failure atomicity so if an immutable object throws an exception, it will not be stuck in an undesirable/indeterminate state
  • They offer higher security
..................Content has been hidden....................

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