HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Why are strings immutable in some languages?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
whyarelanguagesimmutablesomestrings

Problem

String is an immutable class in Java. An immutable class is simply a class whose instances cannot be modified. Why does the Java programming language choose to make objects of class String immutable?

Solution

This issue is strongly connected to the notion of what it means to be an instance of a class. In strict Object-Oriented terms, a class has an associated invariant: a predicate which always holds true on exit from a (public) method of the class. Such a notion is central in ensuring that inheritance is well-defined, for example (it's part of the Liskov Substitution Principle).

One of the most pernicious issues with Java is that it is difficult to prevent client code from breaking class invariants.

For example, consider the following 'ZipCode' class:

class ZipCode {
private String zipCode;

public ZipCode(String value){
if(!isValidZipCode(value))
throw new IllegalArgumentException();
zipCode = value;
assert(invariant());
}

public String get() { return zipCode; }

public boolean invariant() {
return isValidZipCode( zipCode );
}
}


If String were not immutable, it would be possible for a user of ZipCode to call 'get' and change the characters at any subsequent time, thereby breaking the invariant and destroying the conceptual integrity offered by the encapsulation of the ZipCode concept.

Since this kind of integrity is essential to ensuring that large systems are valid, this answer to your question really begs the wider one of:

"Why doesn't Java support an analog of C++ const, or at least offer immutable versions of more of it's library classes?"

Context

StackExchange Computer Science Q#50530, answer score: 9

Revisions (0)

No revisions yet.