Rule 8:Strive for failure atomicity
When the invocation of Method Fails(intermediately), it should leave the object in state it was prior to invocation.
A method with this property is said to be failure-atomic.
Ways to ensure “failure-atomicity”:
1.Make Object Immutable
TODO: Know How it ensures the failureautomacity
2.Method Paramters checks to avoid failure
Example:
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[–size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
If no Checks were applied:-
The exception will still be thrown but will leave the size field in an inconsistent(negative) state.
3.Order of computation – so that the code that may fail is placed before anypart that modifies the object.
This is extension of previous one when the arguments canot be checked before computation.
Example: Let a treeMap had element sorted in aprticular order. inorder to add another element it must be of same type.
so, when tried to add new different type element it throws ClassCasteException as a result of resrching for element in tree, even before the Tree has been modified.
4.Another approach is to maintain the temprory copy of object and replace original with the temproroy once computaion is completed.
5.Last but least common Approach , write a recovery-code that intercepts the failure that occurs in mid of operation and CAUSES the object to rollback it’s state to the point before the operation begins.
This approach is generally used for durable(disk-based) data structure.
Motivation :
Its often both free and easy to achieve faliure atomicity once you ARE AWARE OF THE ISSUE.