berry120 berry120 - 4 years ago 125
Java Question

Would an immutable keyword in Java be a good idea?

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?

Answer Source

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...

  • Easier to write. No messing with final and private, no accidentally adding a method that makes the class mutable, and possibly no manually marking the class final (subclasses can add mutable state).
  • Easier to read. You don't need to say that the class is immutable in English, you can say it in the code itself. An immutable keyword is a good step toward self-documenting code.
  • Faster (theoretically). The more the compiler knows about your code, the more optimizations it can make. Without this keyword, every call to new ImmutableFoo(1, 2, 3) must create a new object, unless the compiler can prove that your class can't be mutated. If ImmutableFoo was marked with the immutable keyword, every such call could return the same object. I'm pretty sure new must 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download