| Start |
|---|
| Creating an immutable version of a type using defensive copying. Some basic types and classes in Java are fundamentally mutable. For example, all array types are mutable, and so are classes like One way to deal with this is to create an immutable wrapper for the mutable type. Here is a simple wrapper for an array of integers This class works by using defensive copying to isolate the mutable state (the We could also add methods to Note that an immutable wrapper type implemented this way is not type compatible with the original type. You cannot simply substitute the former for the latter. |
| The recipe for an immutable class An immutable object is an object whose state cannot be changed. An immutable class is a class whose instances are immutable by design, and implementation. The Java class which is most commonly presented as an example of immutability is java.lang.String (opens new window). The following is a stereotypical example: A variation on this is to declare the constructor as The standard recipe for an immutable class is as follows:
A couple of other things to note:
|
| Typical design flaws which prevent a class from being immutable Using some setters, without setting all needed properties in the constructor(s) It’s easy to show that To fix it, simply delete Not marking instance variables as private and final Take a look at the following class: The following snippet shows that the above class is not immutable: To fix it, simply mark name property as Exposing a mutable object of the class in a getter Take a look at the following class:
This happened because a change to the reference List returned by To fix this, simply avoid returning references that reference class's mutable objects either by making defensive copies, as follows: or by designing getters in way that only other immutable objects and primitives are returned, as follows: Injecting constructor with object(s) that can be modified outside the immutable class This is a variation of the previous flaw. Take a look at the following class: As To fix this, as in the previous flaw, simply make defensive copies of the object without assigning it directly to the immutable class, i.e. constructor can be changed as follows: Letting the methods of the class being overridden Take a look at the following class:
now To fix this, either mark the class as RemarksImmutable objects have fixed state (no setters), so all state must be known at object creation time. Although not technically required, it is best practice to make all fields The examples show several patterns that can assist with achieving this. |
Read Article
https://develop.horje.com/learn/1434/reference