This Item covers several aspects and effects of mutability, but first the (five) basic rules for immutability:
- no methods for object state modification / mutatbility
- ensure that the class can not be extended (either make it final or make all ctors (package)-private and offer static factories, see Item1)
- - make all field final and private (note, this expresses your intend, however it is still possible to mutate them under certain circumstances)
- ensure exclusive access to any mutable components
Immutable classes (ICs) have several properties which a appreciated:
- simple (or trivial ? ;-)
- thread-save out of the box
- and hence can be shared freely
- are building blocks for other classes
- and the JDK has several classes as examples like: String, BigInteger, BigDecimal etc.
- they should (or have to) be small because...
- each distinct value requires a separate object
- in multistep operations you can generate lots of unwanted temporaries
- somewhere in a program, state changes have to happen, or your program will be very trivial ;-)
IMO a possible standard annotation could check for
- antipatterns in ICs, e.g. the shall not have a clong method or cctor.
- ICs shall follow the 5 rules i mentioned in the beginning
- if your IC has a reference to a mutable object, you have to obey
serializability (see Item 76)
- e.g. String provides a copy constructor but ICs should not have a clone method or cctor.
- java.util.Date and java.awt.Point should be ICs but are not.
- String and BigInteger are not so small objects
- The classes in the JDK can NOT be fixed to be ICs because this would break (binary) backward compatiblity (see my link on the eclipse homepage which describes what you can change and what not, I mentioned this in Item 13)
- provide a mutable "companion class" for a IC which enables and optimitzes multistep operations This mutable "companion class" can be package-private or package-public. (e.g. BigInteger, String, and their coresponding companions)
- hide all class ctors and make them private and only offer public static factories (valueOf).
My impression of this chapter:
- pure ICs should be preferred and used if possible
- try to write ICs and hide mutability in companion classes (which are implementation details and shall not be used by clients)
- always try to minimized mutability in "normal API classes".
- there are some defects in JDK ICs as the Java implementors learned also about immutability
- a standard annotation would a.) communicate the intend forimmutability b.) help us the check the esay cases/rules at least
Bernhard Merkle
No comments:
Post a Comment