In object-oriented programming, "Immutable Interface" is a pattern for designing an immutable object. The immutable interface pattern involves defining a type which does not provide any methods which mutate state. Objects which are referenced by that type are not seen to have any mutable state, and appear immutable.
Contents
Java
Consider a Java class which represents a two-dimensional point.
The class Point2D is mutable: its state can be changed after construction, by invoking either of the setter methods (setX()
or setY()
).
An immutable interface for Point2D could be defined as:
By making Point2D implement ImmutablePoint2D, client code could now reference a type which does not have mutating methods, and thus appears immutable. This is demonstrated in the following example:
By referencing only the immutable interface, it is not valid to call a method which mutates the state of the concrete object.
Advantages
Disadvantages
Alternatives
An alternative the immutable interface pattern is the Immutable Wrapper pattern.