Robert

22%
Flag icon
Recall that to guarantee immutability, a class must not permit itself to be subclassed. This can be done by making the class final, but there is another, more flexible alternative. Instead of making an immutable class final, you can make all of its constructors private or package-private and add public static factories in place of the public constructors (Item 1).
Robert
This begins to conflate immutability to protect developers from misusing classes as consumers, with locking down the class to protect it from developers looking to extend functionality. In far too many cases over the years, I've wanted to subclass a class in order take advantage of the classes abilities, but unnecessarily locked down, forcing me to copy/paste a tree of classes. Perhaps a good analogy is cars: designed to shield drivers of the internal operations, and make it easy to use and hard to make mistakes. But many of the screws and bolts are removable; components replaceable and upgradable. Intrepid drivers, if they wish _and at their risk_, may modify their car. Please let us do the same with classes.
Effective Java
Rate this book
Clear rating
Open Preview