dcsimg
Main » TERM » I »

Immutable Definition & Meaning

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.










LATEST ARTICLES
Texting & Chat Abbreviations

From A3 to ZZZ we list 1,559 text message and online chat abbreviations to help you translate and understand today's texting lingo. Includes Top... Read More »

Huge List of Computer Certifications

Have you heard about a computer certification program but can't figure out if it's right for you? Use this handy list to help you decide. Read More »

STUDY GUIDES
Computer Architecture Study Guide

Computer architecture provides an introduction to system design basics for most computer science students. Read More »

Network Fundamentals Study Guide

Networking fundamentals teaches the building blocks of modern network design. Learn different types of networks, concepts, architecture and... Read More »

The Five Generations of Computers

Learn about each of the five generations of computers and major technology developments that have led to the computing devices that we use... Read More »