Generally speaking, the more I use immutable objects in Java the more I’m thinking they’re a great idea. They’ve got lots of advantages from automatically being thread-safe to not needing to worry about cloning or copy constructors.
This has got me thinking, would an “immutable” keyword go amiss? Obviously there’s the disadvantages with adding another reserved word to the language, and I doubt it will actually happen primarily for the above reason – but ignoring that I can’t really see many disadvantages.
At present great care has to be taken to make sure objects are immutable, and even then a dodgy javadoc comment claiming a component object is immutable when it’s in fact not can wreck the whole thing. There’s also the argument that even basic objects like string aren’t truly immutable because they’re easily vunerable to reflection attacks.
If we had an immutable keyword the compiler could surely recursively check and give an iron clad guarantee that all instances of a class were immutable, something that can’t presently be done. Especially with concurrency becoming more and more used, I personally think it’d be good to add a keyword to this effect. But are there any disadvantages or implementation details I’m missing that makes this a bad idea?
In general, immutable objects should be preferred over stateful objects, and it’s currently fairly difficult to make an immutable object in Java. In fact, most OO languages have poor support for immutable objects, while most functional languages take them for granted, such as F#, Haskell, and Clojure.
Adding an immutable keyword to Java could make code…
finalandprivate, no accidentally adding a method that makes the class mutable, and possibly no manually marking the classfinal(subclasses can add mutable state).new ImmutableFoo(1, 2, 3)must create a new object, unless the compiler can prove that your class can’t be mutated. IfImmutableFoowas marked with theimmutablekeyword, every such call could return the same object. I’m pretty surenewmust always create a new object, which makes this point invalid, but effective communication with the compiler is still a good thing.Scala’s case classes are similar to an immutable keyword. An immutable keyword was also being considered in C# 5.