1 Mutability
Mutable : have methods that change the value of the object
Immutable : Once created, they always represent the same value.
- A common use for it is to concatenate a large number of strings together.
- Another is convenient sharing: two parts of your program can communicate more conveniently by sharing a common mutable data structure.
1.1 Risks of mutation
- The answer is that immutable types are safer from bugs, easier to understand, and more ready for change.
- Immutable types are safer from bugs, easier to understand, and more ready for change.
- Passing mutable objects around as parameter **or **return value is a latent bug.
- never use Date Class. Use one of the classes from package java.time : LocalDateTime , Instant , etc. All guarantee in their specifications that they are immutable.
- Aliasing(Mutiple reference) is what makes mutable types risky.
1.2 Specifications for mutating methods
- At this point it should be clear that when a method performs mutation, it is crucial to include that mutation in the method’s spec.
2 Iterating over arrays and lists
- Iterator is an effective design pattern.
- If you want to modify a collection while iterating, use iter.remove() method instead of collection.remove(), because iter.remove() is more efficient and can adjust the index of the collection. For example:
Iterator iter = subjects.iterator();
while (iter.hasNext()) {
String subject = iter.next();
if (subject.startsWith("6.")) {
iter.remove();
//do not call this mehod:
//subjects.remove(subject);
}
}
3 Some Useful immutable types
- The primitive types and primitive wrappers are all immutable.
- Don’t use mutable Date s, use the appropriate immutable type from java.time based on the granularity of timekeeping you need.
- Collections also provides methods for obtaining immutable empty collections: Collections.emptyList , etc.
- The usual implementations of Java’s collections types — List , Set , Map — are all mutable: ArrayList , HashMap , etc. The Collections utility class has methods for obtaining unmodifiable views of these mutable collections:
- Collections.unmodifiableList
- Collections.unmodifiableSet
- Collections.unmodifiableMap
You can think of the unmodifiable view as a wrapper around the underlying list/set/map. A client who has a reference to the wrapper and tries to perform mutations — add , remove , put , etc. — will trigger an UnsupportedOperationException.
Reference
[1] 6.005 — Software Construction on MIT OpenCourseWare | OCW 6.005 Homepage at https://ocw.mit.edu/ans7870/6/6.005/s16/