What Is an Immutable Object?

In object-oriented and functional programming languages, immutable objects are objects that cannot be changed after being created. Objects whose state can be changed are called mutable objects.

Immutable objects are thread-safe. In addition, immutable objects are generally more reasonable, easier to understand, and provide higher security than mutable objects.
Small immutable objects can be efficiently copied, but larger immutable objects need more complex consistent data structure algorithms if they are to be efficiently copied. Because of performance, immutable objects are sometimes replaced by mutable objects.
In Python, Java, and the .NET Framework, strings are immutable objects. Both Java and .NET Framework have variable string versions. In Java, these are StringBuffer and StringBuilder (a mutable version of Java String), and in .NET this is StringBuilder (a mutable version of .Net String). Python 3 has a mutable string (byte) variant called bytearray.
In addition, all primitive wrapper classes in Java are immutable. Similar patterns are immutable interfaces and immutable wrappers.
In purely functional programming languages, it is not possible to create mutable objects without extending the language (for example, through mutable reference libraries or external function interfaces), so all objects are immutable.
In Ada, any object is declared as a variable (that is, mutable; usually an implicit default) or constant (that is, immutable) through the constant keyword.
  type Some_type is new Integer;-could be anything more complicated x: constant Some_type: = 1;-immutable y: Some_type;-mutable
Subroutine parameters are immutable in in mode and variable in in out and out modes.
  procedure Do_it (a: in Integer; b: in out Integer; c: out Integer) is begin-a is immutable b: = b + a; c: = a; end Do_it;
In C ++, Cart's const-correct implementation allows users to declare new instances of a class as const (immutable) or mutable as needed by providing two different versions of the getItems () method [1]
In C #, you can use a readonly statement to enforce the immutability of a field of a class. By forcing all fields to be immutable, you will get immutable types.
  class AnImmutableType {public readonly double _value; public AnImmutableType (double x) {_value = x;} public AnImmutableType Square () {return new AnImmutableType (_value * _value);}}

IN OTHER LANGUAGES

Was this article helpful? Thanks for the feedback Thanks for the feedback

How can we help? How can we help?