Immutable object
Encyclopedia
In object-oriented and functional
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

 programming, an immutable object is an object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

 whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change but the object's state appears to be unchanging from an external point of view. For example, an object that uses memoization
Memoization
In computing, memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously processed inputs...

 to cache the results of expensive computations could still be considered an immutable object.

Immutable objects are often useful because they are inherently thread safe. Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.

However, making an object immutable is usually inappropriate if the object contains a large amount of changeable data. Because of this, many languages allow for both immutable and mutable objects.

Background

Before the advent of OOP
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

, values held in program variables whose content never changed were known as 'constants
Constant (programming)
In computer programming, a constant is an identifier whose associated value cannot typically be altered by the program during its execution...

' to differentiate them from variables that could be altered during execution. Examples might include conversion factors from kilogram weights to pounds or the value of Pi
Pi
' is a mathematical constant that is the ratio of any circle's circumference to its diameter. is approximately equal to 3.14. Many formulae in mathematics, science, and engineering involve , which makes it one of the most important mathematical constants...

 to several decimal places.
In most object-oriented languages
Object-oriented programming language
This is a list of object-oriented programming programming languages.-Languages with object-oriented features:*ABAP*Ada 95*AmigaE*BETA*Blue*Boo*C++*C#*COBOL*Cobra*ColdFusion*Common Lisp*COOL*CorbaScript*Clarion*CLU*Curl*D*Dylan*E*Eiffel...

, objects can be referred to using reference
Reference (computer science)
In computer science, a reference is a value that enables a program to indirectly access a particular data item, such as a variable or a record, in the computer's memory or in some other storage device. The reference is said to refer to the data item, and accessing those data is called...

s. Some examples of such languages are Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

, C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

, C#, VB.NET, and many scripting language
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...

s, such as Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 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 can be copied simply by making a copy of a reference
Reference (computer science)
In computer science, a reference is a value that enables a program to indirectly access a particular data item, such as a variable or a record, in the computer's memory or in some other storage device. The reference is said to refer to the data item, and accessing those data is called...

 to it instead of copying the entire object. Because a reference (typically only the size of a pointer) is usually much smaller than the object itself, this results in memory savings and a boost in execution speed.

The reference copying technique is much more difficult to use for mutable objects, because if any user of a reference to a mutable object changes it, all other users of that reference will 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
Observer pattern
The observer pattern is a software design pattern in which an object, called 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...

 is an alternative technique for handling changes to mutable 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 to be more thread-safe
Thread-safe
Thread safety is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it only manipulates shared data structures in a thread-safe manner, which enables safe execution by multiple threads at the same time...

than mutable objects.

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 integers, are equal. Some languages do this automatically: for example, Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 automatically interns short strings
String intern pool
In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned...

. If the algorithm which 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
Fast path
Fast path is a term used in computer science to describe a path with shorterinstruction path length through a program compared to the 'normal' path. For a fast path to be effective it must handle the most commonly occurring tasks more efficiently than the 'normal' path, leaving the latter to handle...

 case improvement when the objects are equal and use the same reference.) Interning is generally only useful for immutable objects.

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. If all fields are immutable then the object is immutable. 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++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

, final in Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

) which designates the field to be immutable. In some languages, it is reversed: in OCaml, fields of an object or record are by default immutable, and need to be explicitly marked with mutable to be mutable.

Implementation

Immutability does not imply that the object as stored in the computer's memory
Computer storage
Computer data storage, often called storage or memory, refers to computer components and recording media that retain digital data. Data storage is one of the core functions and fundamental components of computers....

 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
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 or C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

).

Scala

In Scala any variable can be defined as mutable or immutable: simply in the declaration one can use val (value) for immutable objects and var (variable) for mutable ones.

E.g. the following code snippet:

val maxValue = 100
var currentValue = 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 immutablilty mean that the new instance can re-use existing nodes, which, especially in the case of creating copies, is very efficient.

Java

A classic example of an immutable object is an instance of the Java String class.


String s = "ABC";
s.toLowerCase;


The method toLowerCase will 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.

By default, fields and local variables are mutable. They can be made immutable using the final keyword.


int i = 42;
i = 43; // OK

final int j = 42;
j = 43; // does not compile

C++

In C++, a const-correct
Const-correctness
In computer science, const-correctness is the form of program correctness that deals with the proper declaration of objects as mutable or immutable. The term is mostly used in a C or C++ context, and takes its name from the const keyword in those languages....

 implementation of Cart would allow the user to declare new instances of the class as either const (immutable) or mutable, as desired, by providing two different versions of the getItems method. (Notice that in C++ it is not necessary — and in fact impossible — to provide a specialized constructor for const instances.)


template
class Cart {
private:
std::vector items;

public:
Cart(const std::vector& v): items(v) { }

std::vector& getItems { return items; }
const std::vector& getItems const { return items; }
int total const { /* return sum of the prices */ }
};


Note that, if there were a field which is a pointer or reference to another object, then it might still be possible to mutate the object pointed to by such a pointer or reference within a const method, without violating const-correctness. It can be argued that in such a case the object is not really immutable.

C++ also provides abstract (as opposed to bitwise) immutability via the mutable keyword, which allows a member variable to be changed from within a const method.


template
class Cart {
private:
std::vector items;
mutable int costInCents;
mutable bool totaled;

public:
Cart(const std::vector& v): items(v), totaled(false) { }

const std::vector& getItems const { return items; }
int total const {
if (!totaled) {
costInCents = 0;
for (std::vector::const_iterator itor = items.begin; itor != items.end; ++itor)
costInCents += itor->costInCents;

totaled = true;
}
return costInCents;
}
};

Perl

In Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

, creating an immutable class requires 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 is usually stored in a hash reference, and can be locked with Hash::Util's lock_hash function):

package Immutable;
use strict;
use warnings;
use base qw(Class::Accessor);
  1. create read-only accessors

__PACKAGE__->mk_ro_accessors(qw(value));
use Hash::Util 'lock_hash';

sub new {
my $class = shift;
return $class if ref($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 data
lock_hash %$obj;
}
1;

Or, with a manually written constructor:

package Immutable;
use strict;
use warnings;
use Hash::Util 'lock_hash';

sub new {
my $class = shift;
return $class if ref($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 data
lock_hash %$obj;
}
  1. read-only accessor

sub value {
my $self = shift;
if (my $new_value = shift) {
# trying to set a new value
die "This object cannot be modified\n";
} else {
return $self->{value}
}
}
1;

Python

In Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 some built-in types (numbers, strings, tuples, frozensets) are immutable, but custom classes are generally mutable. To simulate immutability in a class, one should override attribute setting and deletion to raise exceptions:


class Immutable(object):
"""An immutable class with a single attribute 'value'."""
def __setattr__(self, *args):
raise TypeError("can't modify immutable instance")
__delattr__ = __setattr__
def __init__(self, value):
# we can no longer use self.value = value to store the instance data
# so we must explicitly call the superclass
super(Immutable, self).__setattr__('value', value)

Racket 

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:

(struct foo1 (x y)) ; all fields immutable
(struct foo2 (x [y #:mutable])) ; one mutable field
(struct foo3 (x y) #:mutable) ; all fields mutable

The language also supports immutable hash tables, implemented functionally, and immutable dictionaries.

Ada

In Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...

 any object is declared either variable (then, mutable), or constant (then, immutable), with the constant keyword.

type Some_type is new Integer; -- could be anything more complicated

x: constant Some_type:= 1; -- immutable
y: Some_type; -- mutable

Subprogram parameters are immutable in the in mode, and mutable in the 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;

Copy-on-write

A technique which blends the advantages of mutable and immutable objects, and is supported directly in almost all modern hardware, is copy-on-write
Copy-on-write
Copy-on-write is an optimization strategy used in computer programming. The fundamental idea is that if multiple callers ask for resources which are initially indistinguishable, they can all be given pointers to the same resource...

 (COW). Using this technique, when a user asks the system to copy an object, it will instead merely create a new reference which still points to the same object. As soon as a user modifies the object through a particular reference, the system makes a real copy 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
Virtual memory
In computing, virtual memory is a memory management technique developed for multitasking kernels. This technique virtualizes a computer architecture's various forms of computer data storage , allowing a program to be designed as though there is only one kind of memory, "virtual" memory, which...

 systems because it allows them to save memory space while still correctly handling anything an application program might do.

Usage

Strings and other concrete objects are typically expressed as immutable objects to improve readability and runtime efficiency in object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

. In Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

, Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 and the .NET Framework
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...

, strings are immutable objects. Both Java and the .NET Framework have mutable versions of string. In Java these are StringBuffer and StringBuilder (mutable versions of Java ) and in .NET this is StringBuilder (mutable version of .Net String). Python 3 has a mutable string (bytes) variant, named bytearray.http://docs.python.org/release/3.0/library/functions.html#bytearray
Additionally, all of the primitive wrapper class
Primitive wrapper class
A primitive wrapper class in the Java programming language is one of eight classes provided in the package to provide object methods for the eight primitive types. All of the primitive wrapper classes in Java are immutable...

es in Java are immutable.

Enforcement of the pattern can be checked by using specialized compilers (see for example http://pec.dev.java.net/), and there is a proposal to add immutable types to Java.

Similar patterns are the Immutable Interface
Immutable interface
In object-oriented programming, "Immutable Interface" is a pattern for designing an immutable object. The immutable interface pattern involves defining a type which does not provide any methods which mutate state...

 and Immutable Wrapper.

In pure functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

 languages it is not possible to create mutable objects, so all objects are immutable.

See also

  • Clojure
    Clojure
    Clojure |closure]]") is a recent dialect of the Lisp programming language created by Rich Hickey. It is a general-purpose language supporting interactive development that encourages a functional programming style, and simplifies multithreaded programming....

  • Haskell
    Haskell (programming language)
    Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

  • Erlang
  • Tcl
  • Scala

External links

  • Article "Java theory and practice: To mutate or not to mutate?" by Brian Goetz, from IBM DeveloperWorks
  • Immutable objects from JavaPractices.com
  • Immutable objects from Portland Pattern Repository
    Portland Pattern Repository
    The Portland Pattern Repository is a repository for computer programming design patterns. It was accompanied by a companion website, WikiWikiWeb, which was the world's first wiki....

  • Chapter "Immutable Classes" from a Sather
    Sather
    Sather is an object-oriented programming language. It originated circa 1990 at the International Computer Science Institute at the University of California, Berkeley, developed by an international team led by Steve Omohundro...

     manual, via Berlin Institute of Technology
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK