In object-oriented and functional programming, an immutable object is an object whose state cannot be changed after it is created. The public API of an immutable object guarantees that it will behave in the same way during its lifetime. In some cases, an object is considered immutable even if internally-used attributes change but the object’s state appears unchanged from an external point of view. Below is an example of a basic immutable class:
class User {
private final Long id;
private final String name;
User(Long id, String name) {
this.id = id;
this.name = name;
}
}
All fields are final, meaning that the compiler is told that their values must not change once initialized. All field values are then passed into the constructor.
Immutable object benefits
Since the object is unchangeable, users know exactly what to expect from it. Code cannot be changed, meaning that there’s no opportunity to introduce inconsistencies that may lead to runtime errors. Immutable objects are thread-safe, so synchronization issues are avoided. They are easier to design, implement, and use than mutable classes.
Once an immutable object is created and verified, no other thread or background process will be able to change the object without a user’s direct knowledge. This is useful for programs that need high security. When an issue arises, debugging is easier with immutable objects because a bug’s origin can be easily traced.
Immutable vs. mutable objects
While immutable objects cannot change their state, mutable objects can. Mutable objects provide methods to change an object’s content and are not as thread-safe as immutable objects.
In Java, examples of mutable objects include StringBuilder and java.util.Date. Examples of immutable objects include all legacy classes, wrapper classes, and string classes.
In Python, examples of mutable types include list, dict, and set. Immutable types in Python include int, float, bool, string, unicode, and tuple.