In object-oriented (OO) and functional programming, an immutable object (unchangeable [1] object) is an object whose state cannot be modified after it is created. [2] This is in contrast to a mutable object (changeable object), which can be modified after it is created. [3] In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.
Strings and other concrete objects are typically expressed as immutable objects to improve readability and runtime efficiency in object-oriented programming. Immutable objects are also useful because they are inherently thread-safe. [2] Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects. [2]
In imperative programming, values held in program variables whose content never changes are known as constants to differentiate them from variables that could be altered during execution. Examples include conversion factors from meters to feet, or the value of pi to several decimal places.
Read-only fields may be calculated when the program runs (unlike constants, which are known beforehand), but never change after they are initialized.
Sometimes, one talks of certain fields of an object being immutable. This means that there is no way to change those parts of the object state, even though other parts of the object may be changeable (weakly immutable). If all fields are immutable, then the object is immutable. If the whole object cannot be extended by another class, the object is called strongly immutable. [4] This might, for example, help to explicitly enforce certain invariants about certain data in the object staying the same through the lifetime of the object. In some languages, this is done with a keyword (e.g. const
in C++, final
in Java) that designates the field as immutable. Some languages reverse it: in OCaml, fields of an object or record are by default immutable, and must be explicitly marked with mutable
to be so.
In most object-oriented languages, objects can be referred to using references. Some examples of such languages are Java, C++, C#, VB.NET, and many scripting languages, such as Perl, Python, and Ruby. In this case, it matters whether the state of an object can vary when objects are shared via references.
If an object is known to be immutable, it is preferred to create a reference of it instead of copying the entire object. This is done to conserve memory by preventing data duplication and avoid calls to constructors and destructors; it also results in a potential boost in execution speed.
The reference copying technique is much more difficult to use for mutable objects, because if any user of a mutable object reference changes it, all other users of that reference see the change. If this is not the intended effect, it can be difficult to notify the other users to have them respond correctly. In these situations, defensive copying of the entire object rather than the reference is usually an easy but costly solution. The observer pattern is an alternative technique for handling changes to mutable objects.
A technique that blends the advantages of mutable and immutable objects, and is supported directly in almost all modern hardware, is copy-on-write (COW). Using this technique, when a user asks the system to copy an object, it instead merely creates a new reference that still points to the same object. As soon as a user attempts to modify the object through a particular reference, the system makes a real copy, applies the modification to that, and sets the reference to refer to the new copy. The other users are unaffected, because they still refer to the original object. Therefore, under COW, all users appear to have a mutable version of their objects, although in the case that users do not modify their objects, the space-saving and speed advantages of immutable objects are preserved. Copy-on-write is popular in virtual memory systems because it allows them to save memory space while still correctly handling anything an application program might do.
The practice of always using references in place of copies of equal objects is known as interning . If interning is used, two objects are considered equal if and only if their references, typically represented as pointers or integers, are equal. Some languages do this automatically: for example, Python automatically interns short strings. If the algorithm that implements interning is guaranteed to do so in every case that it is possible, then comparing objects for equality is reduced to comparing their pointers – a substantial gain in speed in most applications. (Even if the algorithm is not guaranteed to be comprehensive, there still exists the possibility of a fast path case improvement when the objects are equal and use the same reference.) Interning is generally only useful for immutable objects.
Immutable objects can be useful in multi-threaded applications. Multiple threads can act on data represented by immutable objects without concern of the data being changed by other threads. Immutable objects are therefore considered more thread-safe than mutable objects.
Immutability does not imply that the object as stored in the computer's memory is unwriteable. Rather, immutability is a compile-time construct that indicates what a programmer can do through the normal interface of the object, not necessarily what they can absolutely do (for instance, by circumventing the type system or violating const correctness in C or C++).
In Python, Java [5] : 80 and the .NET Framework, strings are immutable objects. Both Java and the .NET Framework have mutable versions of string. In Java [5] : 84 these are StringBuffer
and StringBuilder
(mutable versions of Java String
) and in .NET this is StringBuilder
(mutable version of .Net String
). Python 3 has a mutable string (bytes) variant, named bytearray
. [6]
Additionally, all of the primitive wrapper classes in Java are immutable.
Similar patterns are the Immutable Interface and Immutable Wrapper.
In pure functional programming languages it is not possible to create mutable objects without extending the language (e.g. via a mutable references library or a foreign function interface), so all objects are immutable.
In Ada, any object is declared either variable (i.e. mutable; typically the implicit default), or constant
(i.e. immutable) via the constant
keyword.
typeSome_typeisnewInteger;-- could be anything more complicatedx:constantSome_type:=1;-- immutabley:Some_type;-- mutable
Subprogram parameters are immutable in the in mode, and mutable in the in out and out modes.
procedureDo_it(a: inInteger;b: inoutInteger;c: outInteger)isbegin-- a is immutableb:=b+a;c:=a;endDo_it;
In C# you can enforce immutability of the fields of a class with the readonly
statement. [7] : 239 By enforcing all the fields as immutable, you obtain an immutable type.
classAnImmutableType{publicreadonlydouble_value;publicAnImmutableType(doublex){_value=x;}publicAnImmutableTypeSquare(){returnnewAnImmutableType(_value*_value);}}
C# have records which are immutable. [8] [9]
recordPerson(stringFirstName,stringLastName);
In C++, a const-correct implementation of Cart
would allow the user to create instances of the class and then use them as either const
(immutable) or mutable, as desired, by providing two different versions of the items()
method. (Notice that in C++ it is not necessary — and in fact impossible — to provide a specialized constructor for const
instances.)
classCart{public:Cart(std::vector<Item>items):items_(items){}std::vector<Item>&items(){returnitems_;}conststd::vector<Item>&items()const{returnitems_;}intComputeTotalCost()const{/* return sum of the prices */}private:std::vector<Item>items_;};
Note that, when there is a data member that is a pointer or reference to another object, then it is possible to mutate the object pointed to or referenced only within a non-const method.
C++ also provides abstract (as opposed to bitwise) immutability via the mutable
keyword, which lets a member variable be changed from within a const
method.
classCart{public:Cart(std::vector<Item>items):items_(items){}conststd::vector<Item>&items()const{returnitems_;}intComputeTotalCost()const{if(total_cost_){return*total_cost_;}inttotal_cost=0;for(constauto&item:items_){total_cost+=item.Cost();}total_cost_=total_cost;returntotal_cost;}private:std::vector<Item>items_;mutablestd::optional<int>total_cost_;};
In D, there exist two type qualifiers, const
and immutable
, for variables that cannot be changed. [10] Unlike C++'s const
, Java's final
, and C#'s readonly
, they are transitive and recursively apply to anything reachable through references of such a variable. The difference between const
and immutable
is what they apply to: const
is a property of the variable: there might legally exist mutable references to referred value, i.e. the value can actually change. In contrast, immutable
is a property of the referred value: the value and anything transitively reachable from it cannot change (without breaking the type system, leading to undefined behavior). Any reference of that value must be marked const
or immutable
. Basically for any unqualified type T
, const(T)
is the disjoint union of T
(mutable) and immutable(T)
.
classC{/*mutable*/ObjectmField;constObjectcField;immutableObjectiField;}
For a mutable C
object, its mField
can be written to. For a const(C)
object, mField
cannot be modified, it inherits const
; iField
is still immutable as it is the stronger guarantee. For an immutable(C)
, all fields are immutable.
In a function like this:
voidfunc(Cm,constCc,immutableCi){/* inside the braces */}
Inside the braces, c
might refer to the same object as m
, so mutations to m
could indirectly change c
as well. Also, c
might refer to the same object as i
, but since the value then is immutable, there are no changes. However, m
and i
cannot legally refer to the same object.
In the language of guarantees, mutable has no guarantees (the function might change the object), const
is an outward-only guarantee that the function will not change anything, and immutable
is a bidirectional guarantee (the function will not change the value and the caller must not change it).
Values that are const
or immutable
must be initialized by direct assignment at the point of declaration or by a constructor.
Because const
parameters forget if the value was mutable or not, a similar construct, inout
, acts, in a sense, as a variable for mutability information. A function of type const(S) function(const(T))
returns const(S)
typed values for mutable, const and immutable arguments. In contrast, a function of type inout(S) function(inout(T))
returns S
for mutable T
arguments, const(S)
for const(T)
values, and immutable(S)
for immutable(T)
values.
Casting immutable values to mutable inflicts undefined behavior upon change, even if the original value comes from a mutable origin. Casting mutable values to immutable can be legal when there remain no mutable references afterward. "An expression may be converted from mutable (...) to immutable if the expression is unique and all expressions it transitively refers to are either unique or immutable." [10] If the compiler cannot prove uniqueness, the casting can be done explicitly and it is up to the programmer to ensure that no mutable references exist.
The type string
is an alias for immutable(char)[]
, i.e. a typed slice of memory of immutable characters. [11] Making substrings is cheap, as it just copies and modifies a pointer and a length filed, and safe, as the underlying data cannot be changed. Objects of type const(char)[]
can refer to strings, but also to mutable buffers.
Making a shallow copy of a const or immutable value removes the outer layer of immutability: Copying an immutable string (immutable(char[])
) returns a string (immutable(char)[]
). The immutable pointer and length are being copied and the copies are mutable. The referred data has not been copied and keeps its qualifier, in the example immutable
. It can be stripped by making a depper copy, e.g. using the dup
function.
A classic example of an immutable object is an instance of the Java String
class
Strings="ABC";s.toLowerCase();// This accomplishes nothing!
The method toLowerCase()
does not change the data "ABC" that s
contains. Instead, a new String object is instantiated and given the data "abc" during its construction. A reference to this String object is returned by the toLowerCase()
method. To make the String s
contain the data "abc", a different approach is needed:
s=s.toLowerCase();
Now the String s
references a new String object that contains "abc". There is nothing in the syntax of the declaration of the class String that enforces it as immutable; rather, none of the String class's methods ever affect the data that a String object contains, thus making it immutable.
The keyword final
(detailed article) is used in implementing immutable primitive types and object references, [12] but it cannot, by itself, make the objects themselves immutable. See below examples:
Primitive type variables (int
, long
, short
, etc.) can be reassigned after being defined. This can be prevented by using final
.
inti=42;//int is a primitive typei=43;// OKfinalintj=42;j=43;// does not compile. j is final so can't be reassigned
Reference types cannot be made immutable just by using the final
keyword. final
only prevents reassignment.
finalMyObjectm=newMyObject();//m is of reference typem.data=100;// OK. We can change state of object m (m is mutable and final doesn't change this fact)m=newMyObject();// does not compile. m is final so can't be reassigned
Primitive wrappers (Integer
, Long
, Short
, Double
, Float
, Character
, Byte
, Boolean
) are also all immutable. Immutable classes can be implemented by following a few simple guidelines. [13]
In JavaScript, all primitive types (Undefined, Null, Boolean, Number, BigInt, String, Symbol) are immutable, but custom objects are generally mutable.
functiondoSomething(x){/* does changing x here change the original? */};varstr='a string';varobj={an:'object'};doSomething(str);// strings, numbers and bool types are immutable, function gets a copydoSomething(obj);// objects are passed in by reference and are mutable inside functiondoAnotherThing(str,obj);// `str` has not changed, but `obj` may have.
To simulate immutability in an object, one may define properties as read-only (writable: false).
varobj={};Object.defineProperty(obj,'foo',{value:'bar',writable:false});obj.foo='bar2';// silently ignored
However, the approach above still lets new properties be added. Alternatively, one may use Object.freeze to make existing objects immutable.
varobj={foo:'bar'};Object.freeze(obj);obj.foo='bars';// cannot edit property, silently ignoredobj.foo2='bar2';// cannot add property, silently ignored
With the implementation of ECMA262, JavaScript has the ability to create immutable references that cannot be reassigned. However, using a const
declaration doesn't mean that value of the read-only reference is immutable, just that the name cannot be assigned to a new value.
constALWAYS_IMMUTABLE=true;try{ALWAYS_IMMUTABLE=false;}catch(err){console.log("Can't reassign an immutable reference.");}constarr=[1,2,3];arr.push(4);console.log(arr);// [1, 2, 3, 4]
The use of immutable state has become a rising trend in JavaScript since the introduction of React, which favours Flux-like state management patterns such as Redux. [14]
In Perl, one can create an immutable class with the Moo library by simply declaring all the attributes read only:
packageImmutable;useMoo;hasvalue=>(is=>'ro',# read onlydefault=>'data',# can be overridden by supplying the constructor with# a value: Immutable->new(value => 'something else'););1;
Creating an immutable class used to require two steps: first, creating accessors (either automatically or manually) that prevent modification of object attributes, and secondly, preventing direct modification of the instance data of instances of that class (this was usually stored in a hash reference, and could be locked with Hash::Util's lock_hash function):
packageImmutable;usestrict;usewarnings;usebaseqw(Class::Accessor);# create read-only accessors__PACKAGE__->mk_ro_accessors(qw(value));useHash::Util'lock_hash';subnew{my$class=shift;return$classifref($class);die"Arguments to new must be key => value pairs\n"unless(@_%2==0);my%defaults=(value=>'data',);my$obj={%defaults,@_,};bless$obj,$class;# prevent modification of the object datalock_hash%$obj;}1;
Or, with a manually written accessor:
packageImmutable;usestrict;usewarnings;useHash::Util'lock_hash';subnew{my$class=shift;return$classifref($class);die"Arguments to new must be key => value pairs\n"unless(@_%2==0);my%defaults=(value=>'data',);my$obj={%defaults,@_,};bless$obj,$class;# prevent modification of the object datalock_hash%$obj;}# read-only accessorsubvalue{my$self=shift;if(my$new_value=shift){# trying to set a new valuedie"This object cannot be modified\n";}else{return$self->{value}}}1;
In PHP have readonly properties since version 8.1 and readonly classes since version 8.2. [15] [16]
readonlyclassBlogData{publicstring$title;publicStatus$status;publicfunction__construct(string$title,Status$status){$this->title=$title;$this->status=$status;}}
In Python, some built-in types (numbers, Booleans, strings, tuples, frozensets) are immutable, but custom classes are generally mutable. To simulate immutability in a class, one could override attribute setting and deletion to raise exceptions:
classImmutablePoint:"""An immutable class with two attributes 'x' and 'y'."""__slots__=['x','y']def__setattr__(self,*args):raiseTypeError("Can not modify immutable instance.")__delattr__=__setattr__def__init__(self,x,y):# We can no longer use self.value = value to store the instance data# so we must explicitly call the superclasssuper().__setattr__('x',x)super().__setattr__('y',y)
The standard library helpers collections.namedtuple
and typing.NamedTuple
, available from Python 3.6 onward, create simple immutable classes. The following example is roughly equivalent to the above, plus some tuple-like features:
fromtypingimportNamedTupleimportcollectionsPoint=collections.namedtuple('Point',['x','y'])# the following creates a similar namedtuple to the aboveclassPoint(NamedTuple):x:inty:int
Introduced in Python 3.7, dataclasses
allow developers to emulate immutability with frozen instances. If a frozen dataclass is built, dataclasses
will override __setattr__()
and __delattr__()
to raise FrozenInstanceError
if invoked.
fromdataclassesimportdataclass@dataclass(frozen=True)classPoint:x:inty:int
Racket substantially diverges from other Scheme implementations by making its core pair type ("cons cells") immutable. Instead, it provides a parallel mutable pair type, via mcons
, mcar
, set-mcar!
etc. In addition, many immutable types are supported, for example, immutable strings and vectors, and these are used extensively. New structs are immutable by default, unless a field is specifically declared mutable, or the whole struct:
(structfoo1(xy)); all fields immutable(structfoo2(x[y#:mutable])); one mutable field(structfoo3(xy)#:mutable); all fields mutable
The language also supports immutable hash tables, implemented functionally, and immutable dictionaries.
Rust's ownership system allows developers to declare immutable variables, and pass immutable references. By default, all variables and references are immutable. Mutable variables and references are explicitly created with the mut
keyword.
Constant items in Rust are always immutable.
// constant items are always immutableconstALWAYS_IMMUTABLE: bool=true;structObject{x: usize,y: usize,}fnmain(){// explicitly declare a mutable variableletmutmutable_obj=Object{x: 1,y: 2};mutable_obj.x=3;// okayletmutable_ref=&mutmutable_obj;mutable_ref.x=1;// okayletimmutable_ref=&mutable_obj;immutable_ref.x=3;// error E0594// by default, variables are immutableletimmutable_obj=Object{x: 4,y: 5};immutable_obj.x=6;// error E0596letmutable_ref2=&mutimmutable_obj;// error E0596letimmutable_ref2=&immutable_obj;immutable_ref2.x=6;// error E0594}
In Scala, any entity (narrowly, a binding) can be defined as mutable or immutable: in the declaration, one can use val
(value) for immutable entities and var
(variable) for mutable ones. Note that even though an immutable binding can not be reassigned, it may still refer to a mutable object and it is still possible to call mutating methods on that object: the binding is immutable, but the underlying object may be mutable.
For example, the following code snippet:
valmaxValue=100varcurrentValue=1
defines an immutable entity maxValue
(the integer type is inferred at compile-time) and a mutable entity named currentValue
.
By default, collection classes such as List
and Map
are immutable, so update-methods return a new instance rather than mutating an existing one. While this may sound inefficient, the implementation of these classes and their guarantees of immutability mean that the new instance can re-use existing nodes, which, especially in the case of creating copies, is very efficient. [17] [ better source needed ]
In multi-threaded computer programming, a function is thread-safe when it can be invoked or accessed concurrently by multiple threads without causing unexpected behavior, race conditions, or data corruption. As in the multi-threaded context where a program executes several threads simultaneously in a shared address space and each of those threads has access to every other thread's memory, thread-safe functions need to ensure that all those threads behave properly and fulfill their design specifications without unintended interaction.
In computer programming, the flyweight software design pattern refers to an object that minimizes memory usage by sharing some of its data with other similar objects. The flyweight pattern is one of twenty-three well-known GoF design patterns. These patterns promote flexible object-oriented software design, which is easier to implement, change, test, and reuse.
In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
In computer programming, a parameter or a formal argument is a special kind of variable used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are the values of the arguments with which the subroutine is going to be called/invoked. An ordered list of parameters is usually included in the definition of a subroutine, so that, each time the subroutine is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.
In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. In some languages, particularly C++, function objects are often called functors.
In computer programming, foreach loop is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.
In class-based, object-oriented programming, a constructor is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.
In some programming languages, const is a type qualifier that indicates that the data is read-only. While this can be used to declare constants, const in the C family of languages differs from similar constructs in other languages in that it is part of the type, and thus has complicated behavior when combined with pointers, references, composite data types, and type-checking. In other languages, the data is not in a single memory location, but copied at compile time for each use. Languages which use it include C, C++, D, JavaScript, Julia, and Rust.
In the Java programming language, the final
keyword is used in several contexts to define an entity that can only be assigned once.
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.
The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted. The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages. It supports multiple programming paradigms, including structured, object-oriented programming, and functional programming, and boasts a dynamic type system and automatic memory management.
C++11 is a version of a joint technical standard, ISO/IEC 14882, by the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC), for the C++ programming language. C++11 replaced the prior version of the C++ standard, named C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.
In computer science, a value object is a small object that represents a simple entity whose equality is not based on identity: i.e. two value objects are equal when they have the same value, not necessarily being the same object.
In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.
In certain computer programming languages, data types are classified as either value types or reference types, where reference types are always implicitly accessed via references, whereas value type variables directly contain the values themselves.
This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.
This comparison of programming languages (associative arrays) compares the features of associative array data structures or array-lookup processing for over 40 computer programming languages.
In computer programming, a constant is a value that is not altered by the program during normal execution. When associated with an identifier, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably. This is contrasted with a variable, which is an identifier with a value that can be changed during normal execution. To simplify, constants' values remains, while the values of variables varies, hence both their names.
In the context of programming languages, a type qualifier is a keyword that can be used to annotate a type to instruct the compiler to treat the now qualified type in a special way.
A strongly typed identifier is user-defined data type which serves as an identifier or key that is strongly typed. This is a solution to the "primitive obsession" code smell as mentioned by Martin Fowler. The data type should preferably be immutable if possible. It is common for implementations to handle equality testing, serialization and model binding.
This article contains some material from the Perl Design Patterns Book
The preferred way is to make the class final. This is sometimes referred to as "Strong Immutability". It prevents anyone from extending your class and accidentally or deliberately making it mutable.