What is immutability?
Immutability means that values and objects that you are working with cannot be altered.
This means that you can rely on the values or objects that you receive to be the same and not get altered by outside forces.
This does lead to predictable and stable code that can also easily be tested.
Rules of thumb for creating immutable objects
- Class cannot be extended
- Although this is controversial, extending an object, does mean that there is an option to create a mutable version of it.
- Class does not expose it’s fields
- Exposed fields can be mutated
- Methods exposing data return copies from the stored data
- Copies of the data can be mutated and used without affecting the data stored inside the immutable object.
- When constructing the immutable object, copies of the supplied data should be stored.
- As the immutable object does not have control of the data that is supplied to it, it can be mutated.
- Mutating methods return a copy of the object
Rules of thumb for immutable code
- Variables should be immutable
- Objects should be immutable
- When working with return values from a method, store them in a local immutable variable before using it in multiple places.
Examples
These are examples here to show how immutability works. Not all best practices in coding are supplied in here for simplicity sake.
EmailAddress
// The class is final so it cannot be extended
public final class EmailAddress {
// These fields are private so they cannot be altered from the outside
private String tld;
private String domain;
private String user;
// The constructor stores copies of the supplied data
public Email(String tld, String domain, String user) {
this.tld = String.copyValueOf(tld);
this.domain = String.copyValueOf(domain);
this.user = String.copyValueOf(user);
}
// The methods return copies of the contained values.
// There is no need for the methods te be final, as the class is already final.
public int tld() {
return String.copyValueOf(this.tld);
}
public int domain() {
return String.copyValueOf(this.domain);
}
public int user() {
return String.copyValueOf(this.user);
}
// The new combined email address does make it a new string.
// Thus, no exclicit copy needs to be created
public int email() {
return this.user + "@" + this.domain + "." + this.tld;
}
// This mutating method actually returns a new Object
public Email withDomain(String domain) {
return new Email(this.tld, domain, this.user);
}
}
JavaLinks
https://www.baeldung.com/java-immutable-object
https://www.javatpoint.com/mutable-and-immutable-in-java
https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
One Reply to “Immutability”
Comments are closed.