Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
ITEM 15: MINIMIZE MUTABILITY 73 Item 15: Minimize mutability An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String , the boxed primitive classes, and BigInte- ger and BigDecimal . There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure. To make a class immutable, follow these five rules: 1. Don't provide any methods that modify the object's state (known as muta- tors). 2. Ensure that the class can't be extended. This prevents careless or malicious subclasses from compromising the immutable behavior of the class by behav- ing as if the object's state has changed. Preventing subclassing is generally ac- complished by making the class final, but there is an alternative that we'll