Mutable Objects: When the contents of instance can be changed.
Example - StringBuffer
Immutable Objects: When the contents of instance cannot be changed.
Example - String, Integer, Float
Advantages of immutable classes/object
1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronization is avoided.
2) Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
3) The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
4) The best use of the immutable objects is as the keys of a map.
Building an Immutable class
1. Remove all the mutators
If we removed all of the mutators from the class, would it be Immutable?
No! it wouldn't.
Removing mutators is a necessary first step, but immutability requires more than that to ensure that the contents of an instance never changes.
2. Fields must be private
This is almost enough, but there are two more steps to consider.
3. Make sure class can't be extended or methods can't be overridden
If your class gets extended, it could add extra fields that are not immutable, or the methods could be overridden to return a different value each time.
There are two ways to protect against this :
1. Strong immutability : Make class final (preferred way)
2. Weak immutability : Make methods final (Allow class to be extended but protects the original contract specified by the class)
4. Protect mutable fields
Build your immutable class from primitive types or immutable fields, otherwise (for example : java.util.Date type field) you have to protect mutable fields from manipulation.
If a field isn't primitive or immutable, make deep copies of mutable data.
When you copy the instance on the way in and the way out, you need to make a deep copy. Otherwise you run the risk of leaving some mutable data in your immutable class.
Example
// RULE 1 - Make the class final (Strong immutability) ;
// otherwise, You can make all the methods final (Weak immutability)
public final class Employee {
// RULE 2 - Make all fields private
private int empId;
private String empName;
private java.util.Date joiningDate;
// RULE 3 - Don't provide mutators (setters) for fields
// Keeping accessors (getters) are safe
public int getEmpId() {
return empId;
}
public String getEmpName() {
return empName;
}
// RULE 4 - Protect mutable fields from manipulation :
// Make deep copies of mutable data
public String getJoiningDate() {
return new java.util.Date( joiningDate.getTime() );
}
}
Guidelines
Setters and getters, along with properties should only be created when you find you need them and Not every by default.
You may be needing getters pretty regularly, so keep them.
Setters or writable properties should ever exist in your code through a builder pattern where they are locked down after the object has been completely instantiated.
Programmer should keep in mind that setter is almost same as directly manipulating the property.
Which Java classes are Immutable ?
- All of the java.lang package wrapper classes : Boolean, Byte, Character, Double, Float, Integer, Long, Short
- String claas
Where to use immutable objects ?
Where we need a value or fixed instance, Like :
1. A color is usually thought of as a value, thus the immutable Color class. (i.e. Green color is a fixed color and cannot represent other color)
2. A playing card that has a fixed unchanging suit and rank once created (i.e. Paan ka Ikka)
3. Classes for representing complex numbers or arbitrary-precision rational numbers can be immutable.
4. Abstract types which contains many discrete values, such as vectors or matrices.
Where not to use ?
1. The fuel capacity and speed of a car would keep on changing in a racing game, hence making Car object immutable and keep on creating new instances while the state changes is not meaningful.
You have to avoid creating immutable objects in this case.
2. All above mentioned immutable objects, could also be defined mutable depending on their usage and need in application.
Why we don’t see immutable objects in our application ?
1. Programmers don't know when and how to use immutability because they are not familiar with it.
2. Many programers learn how to program using an imperative (procedural or object-oriented) paradigm, therefore mutability is their basic approach.
Programmers assumes that generating getters/setters both for all properties of class is the part of OOPs programming.
It's a mindset
3. Using automatic getter / setter generation facility in all Java programming IDEs does not consider the requirement of avoidable methods.
4. For programmers, it is often more effective to first focus on writing a program that is functionally correct, and then try to find bottlenecks and optimize it.
They think immutability is a part of optimization.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.