Update: I almost forgot Doug Lea's thoughtful design and implementation of a collection package, which predates the java.util collections. That specific link will take you directly to his wisdom on designing type checked immutability. (Which makes me wonder if Microsoft has hired him yet too?!)
Greg Schecter writes about the
Changeable class. Not knowing much about the implementation this seems like a reasonable concept. (
EmeddedChangeableReader sounds like it might be a bit over the top, but I don't know.)
Compare this to
Object.freeze in Ruby. The Ruby implementation appears to be simpler, but the overall lesson I think is this: what we have in the
Changeable class is more evidence of Java-like languages struggling with their underlying dynamic tendencies.
Inside every statically type checked language there is a dynamic language struggling to get out.
The simple statically checked approach is to create a class without mutation, e.g.
Brush, and then add mutation in the subclass, e.g.
MutableBrush. Another approach is to simply throw an exception in a method that would otherwise cause a mutation without any system-wide designation in the code. See the Java Collections API for example. In particular the
unmodifiableCollection static method and its siblings for
Then again there is the option of just allowing mutation for all instances even when it's not expected. One of the first actions I took in my first Smalltalk system (the Tek 4404) was to change Black to White. Oops. Fortunately although Smalltalk has a persistent image, it's not difficult to back out of the change.