Information about Immutable Object
In object-oriented and functional programming, an immutable object is an object 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. An object can be either entirely immutable or some attributes in the object may be declared immutable; for example, using the const member data attribute in the C++ programming language. 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 to cache the results of expensive computations could still be considered an immutable object. The initial state of an immutable object is usually set at its inception, but can also be set before actual use of the object.
Immutable objects are often useful because some costly operations for copying and comparing can be omitted, simplifying the program code and speeding execution. 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.
If an object is known to be immutable, it can be copied simply by making a copy of a reference 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 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 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 automatically interns strings. 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 case improvement when the objects are equal and use the same reference.) Interning is generally only useful for immutable objects.
A classic example of an immutable object is an instance of the Java
String s = "ABC"; s.toLowerCase();
The method
s = s.toLowerCase();
Now the String
For an object to be immutable, there has to be no way to change fields, mutable or not, and to access fields that are mutable. Here is an example of a mutable object written in the Java programming language.
A technique which 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 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 systems because it allows them to save memory space in the core while still correctly handling anything an application program might do.
Additionally, all of the primitive wrapper classes in Java are immutable.
Enforcement of the pattern can be checked by using specialized compilers (see for example [1]), and there is a proposal to add immutable types to Java.
Similar patterns are the Immutable Interface and Immutable Wrapper.
In pure functional programming languages it is not possible to create mutable objects, so all objects are immutable.
Scripting languages (commonly called script languages) are computer programming languages that are typically interpreted and can be typed directly from a keyboard.
..... Click the link for more information.
Immutable objects are often useful because some costly operations for copying and comparing can be omitted, simplifying the program code and speeding execution. 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
In most object-oriented languages, objects can be referred to using references. Some examples of such languages are Java, C++,C Sharp,VB.NET and many scripting languages, such as Python and Ruby. In this case, it matters whether the state of 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 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 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 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 automatically interns strings. 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 case improvement when the objects are equal and use the same reference.) Interning is generally only useful for immutable objects.
Implementation
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 should do, not necessarily what he can do (for instance, by circumventing the type system or violating const correctness in C or C++).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". The String class's methods never affect the data that a String object contains.
For an object to be immutable, there has to be no way to change fields, mutable or not, and to access fields that are mutable. Here is an example of a mutable object written in the Java programming language.
>
class Cart {
private final List items;
public Cart(List items) { this.items = items; }
public List getItems() { return items; }
public int total() { /* return sum of the prices */ }
}
An instance of this class is not immutable: one can add or remove items either by obtaining the field items by calling getItems() or by retaining a reference to the List object passed when an object of this class is created. The following change partially solves this problem. In the ImmutableCart class, the list is immutable: you cannot add or remove items. However, there is no guarantee that the items are also immutable. One solution is to use the decorator pattern as a wrapper around each of the list's items to make them also immutable.
>
class ImmutableCart {
private final List items;
public ImmutableCart(List items) {
this.items = Arrays.asList(items.toArray());
}
public List getItems() {
return Collections.unmodifiableList(items);
}
public int total() { /* return sum of the prices */ }
}
In C++, a const-correct 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++, which lacks automatic garbage collection, it is idiomatic to make a copy of the constructor parameter v rather than keeping only a reference to it, as in the Java code above. Therefore, the C++ code needs only to const-qualify the result of
getItems(); it is not necessary — and in fact impossible — to provide a specialized constructor for const instances.)
> templateIn Python some built-in types are immutable, but custom classes are generally mutable. To create an immutable class, one should override attribute setting and deletion to raise exceptions:class Cart { private: std::vector items; public: Cart(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 */ } };
>
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)
A technique which 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 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 systems because it allows them to save memory space in the core 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. In Python, Java and the .NET Framework, 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 JavaString) and in .NET this is StringBuilder (mutable version of .Net String).
Additionally, all of the primitive wrapper classes in Java are immutable.
Enforcement of the pattern can be checked by using specialized compilers (see for example [1]), and there is a proposal to add immutable types to Java.
Similar patterns are the Immutable Interface and Immutable Wrapper.
In pure functional programming languages it is not possible to create mutable objects, so all objects are immutable.
External links
- Article "Pattern: Immutable Object" by Nat Pryce
- Article "Java theory and practice: To mutate or not to mutate?" by Brian Goetz
- Java Reference Java Practices: Immutable objects
- Chapter "Immutability of Objects" in the Common Lisp Interface Manager Specification
- Chapter "Immutable Classes" from a Sather manual
Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. It is based on several techniques, including inheritance, modularity, polymorphism, and encapsulation.
..... Click the link for more information.
..... Click the link for more information.
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
..... Click the link for more information.
const keyword in those languages...... Click the link for more information.
C++
Paradigm: Multi-paradigm
Appeared in: 1983
Designed by: Bjarne Stroustrup
Typing discipline: Static, unsafe, nominative
Major implementations: G++, Microsoft Visual C++, Borland C++ Builder
Dialects: ISO/IEC C++ 1998, ISO/IEC C++ 2003
..... Click the link for more information.
Paradigm: Multi-paradigm
Appeared in: 1983
Designed by: Bjarne Stroustrup
Typing discipline: Static, unsafe, nominative
Major implementations: G++, Microsoft Visual C++, Borland C++ Builder
Dialects: ISO/IEC C++ 1998, ISO/IEC C++ 2003
..... Click the link for more information.
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.
..... Click the link for more information.
..... Click the link for more information.
In computer science, the object lifetime (or life cycle) of an object in object-oriented programming is the time between an object's creation (also known as instantiation or construction) till the object is no longer used, and is destructed or
..... Click the link for more information.
..... Click the link for more information.
An object-oriented programming language (also called an OO language) is one that allows or encourages, to some degree, object-oriented programming techniques such as encapsulation, inheritance, interfaces, and polymorphism.
..... Click the link for more information.
..... Click the link for more information.
reference is an object containing information which refers to data stored elsewhere, as opposed to containing the data itself. Accessing the value referred to by a reference is called dereferencing it.
..... Click the link for more information.
..... Click the link for more information.
Java
Paradigm: Object-oriented, structured, imperative
Appeared in: 1995
Designed by: Sun Microsystems
Typing discipline: Static, strong, safe, nominative
Major implementations: Numerous
Influenced by: Objective-C, C++, Smalltalk, Eiffel,[1]
..... Click the link for more information.
Paradigm: Object-oriented, structured, imperative
Appeared in: 1995
Designed by: Sun Microsystems
Typing discipline: Static, strong, safe, nominative
Major implementations: Numerous
Influenced by: Objective-C, C++, Smalltalk, Eiffel,[1]
..... Click the link for more information.
C++
Paradigm: Multi-paradigm
Appeared in: 1983
Designed by: Bjarne Stroustrup
Typing discipline: Static, unsafe, nominative
Major implementations: G++, Microsoft Visual C++, Borland C++ Builder
Dialects: ISO/IEC C++ 1998, ISO/IEC C++ 2003
..... Click the link for more information.
Paradigm: Multi-paradigm
Appeared in: 1983
Designed by: Bjarne Stroustrup
Typing discipline: Static, unsafe, nominative
Major implementations: G++, Microsoft Visual C++, Borland C++ Builder
Dialects: ISO/IEC C++ 1998, ISO/IEC C++ 2003
..... Click the link for more information.
C#
Paradigm: structured, imperative, object-oriented
Appeared in: 2001 (last revised 2005)
Designed by: Microsoft Corporation
Typing discipline: static, strong, both safe and unsafe, nominative
Major implementations: .NET Framework, Mono, DotGNU
Dialects: 1.
..... Click the link for more information.
Paradigm: structured, imperative, object-oriented
Appeared in: 2001 (last revised 2005)
Designed by: Microsoft Corporation
Typing discipline: static, strong, both safe and unsafe, nominative
Major implementations: .NET Framework, Mono, DotGNU
Dialects: 1.
..... Click the link for more information.
- Scripting redirects here. For other uses, see script.
Scripting languages (commonly called script languages) are computer programming languages that are typically interpreted and can be typed directly from a keyboard.
..... Click the link for more information.
Python
Paradigm: Multi-paradigm
Appeared in: 1991
Designed by: Guido van Rossum
Developer: Python Software Foundation
Latest release: 2.5.1/ April 18 2007
Latest unstable release: 3.
..... Click the link for more information.
Paradigm: Multi-paradigm
Appeared in: 1991
Designed by: Guido van Rossum
Developer: Python Software Foundation
Latest release: 2.5.1/ April 18 2007
Latest unstable release: 3.
..... Click the link for more information.
Ruby
Paradigm: multi-paradigm (functional, imperative, logic, object-oriented (class-based))
Appeared in: 1995
Designed by: Yukihiro Matsumoto
Developer: Yukihiro Matsumoto (among others)
Latest release: 1.8.
..... Click the link for more information.
Paradigm: multi-paradigm (functional, imperative, logic, object-oriented (class-based))
Appeared in: 1995
Designed by: Yukihiro Matsumoto
Developer: Yukihiro Matsumoto (among others)
Latest release: 1.8.
..... Click the link for more information.
reference is an object containing information which refers to data stored elsewhere, as opposed to containing the data itself. Accessing the value referred to by a reference is called dereferencing it.
..... Click the link for more information.
..... Click the link for more information.
pointer is a programming language data type whose value refers directly to (or “points to”) another value stored elsewhere in the computer memory using its address. Obtaining the value to which a pointer refers is called dereferencing the pointer.
..... Click the link for more information.
..... Click the link for more information.
One of the most common procedures that occurs in computer programs is the copying of data. An object is a composite data type in object-oriented programming languages. Object copy thus describes the action wherein an object has its attributes copied to another object of the same data type.
..... Click the link for more information.
..... Click the link for more information.
The observer pattern (sometimes known as publish/subscribe) is a design pattern used in computer programming to observe the state of an object in a program. It is related to the principle of implicit invocation.
..... Click the link for more information.
..... Click the link for more information.
Thread safety is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads.
..... Click the link for more information.
..... Click the link for more information.
Python
Paradigm: Multi-paradigm
Appeared in: 1991
Designed by: Guido van Rossum
Developer: Python Software Foundation
Latest release: 2.5.1/ April 18 2007
Latest unstable release: 3.
..... Click the link for more information.
Paradigm: Multi-paradigm
Appeared in: 1991
Designed by: Guido van Rossum
Developer: Python Software Foundation
Latest release: 2.5.1/ April 18 2007
Latest unstable release: 3.
..... Click the link for more information.
Computer data storage, computer memory, and often casually storage or memory refer to computer components, devices and recording media that retain digital data used for computing for some interval of time.
..... Click the link for more information.
..... Click the link for more information.
In computer science, compile time refers to either the operations performed by a compiler (ie, compile-time operations) or programming language requirements that must be met by source code for it to be successfully compiled (ie, compile-time requirements).
..... Click the link for more information.
..... Click the link for more information.
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
..... Click the link for more information.
const keyword in those languages...... Click the link for more information.
C
The C Programming Language, Brian Kernighan and Dennis Ritchie, the original edition that served for many years as an informal specification of the language.
..... Click the link for more information.
The C Programming Language, Brian Kernighan and Dennis Ritchie, the original edition that served for many years as an informal specification of the language.
..... Click the link for more information.
C++
Paradigm: Multi-paradigm
Appeared in: 1983
Designed by: Bjarne Stroustrup
Typing discipline: Static, unsafe, nominative
Major implementations: G++, Microsoft Visual C++, Borland C++ Builder
Dialects: ISO/IEC C++ 1998, ISO/IEC C++ 2003
..... Click the link for more information.
Paradigm: Multi-paradigm
Appeared in: 1983
Designed by: Bjarne Stroustrup
Typing discipline: Static, unsafe, nominative
Major implementations: G++, Microsoft Visual C++, Borland C++ Builder
Dialects: ISO/IEC C++ 1998, ISO/IEC C++ 2003
..... Click the link for more information.
Java
Paradigm: Object-oriented, structured, imperative
Appeared in: 1995
Designed by: Sun Microsystems
Typing discipline: Static, strong, safe, nominative
Major implementations: Numerous
Influenced by: Objective-C, C++, Smalltalk, Eiffel,[1]
..... Click the link for more information.
Paradigm: Object-oriented, structured, imperative
Appeared in: 1995
Designed by: Sun Microsystems
Typing discipline: Static, strong, safe, nominative
Major implementations: Numerous
Influenced by: Objective-C, C++, Smalltalk, Eiffel,[1]
..... Click the link for more information.
decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing method of an object dynamically.
..... Click the link for more information.
Introduction
The decorator pattern works by wrapping the new "decorator" object around the original object, which is typically..... Click the link for more information.
In computer programming, the adapter design pattern (often referred to as the wrapper pattern or simply a wrapper) 'adapts' one interface for a class into one that a client expects.
..... Click the link for more information.
..... Click the link for more information.
In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that will never be accessed or mutated again by the application.
..... Click the link for more information.
..... Click the link for more information.
Python
Paradigm: Multi-paradigm
Appeared in: 1991
Designed by: Guido van Rossum
Developer: Python Software Foundation
Latest release: 2.5.1/ April 18 2007
Latest unstable release: 3.
..... Click the link for more information.
Paradigm: Multi-paradigm
Appeared in: 1991
Designed by: Guido van Rossum
Developer: Python Software Foundation
Latest release: 2.5.1/ April 18 2007
Latest unstable release: 3.
..... Click the link for more information.
Copy-on-write (sometimes referred to as "COW") is an optimization strategy used in computer programming. The fundamental idea is that if multiple callers ask for resources which are initially indistinguishable, you can give them pointers to the same resource.
..... Click the link for more information.
..... Click the link for more information.
This article is copied from an article on Wikipedia.org - the free encyclopedia created and edited by online user community. The text was not checked or edited by anyone on our staff. Although the vast majority of the wikipedia encyclopedia articles provide accurate and timely information please do not assume the accuracy of any particular article. This article is distributed under the terms of GNU Free Documentation License.
Herod_Archelaus