I have read that with a Java version less than 7, Joda Time objects are more reliable than Java’s built-ins. One cited reason is that Joda objects are immutable. Why is this beneficial? If I want to change the year, hour, and timezone of a Joda DateTime object, I need to make three copies!
Share
Yes, indeed. Or you could create one new object, using all the fields you like from the old object, of course.
This is a thoroughly good thing – because it means when you want to rely on an object not changing, it won’t. Consider this pseudo-code:
That’s fine, because
Instantis immutable. If it were mutable, the validation in the constructor would be worthless – unless you created a defensive copy at that point.In my experience, you want to pass around references and know that the values won’t change more than you want to actually make changes to existing objects, so immutability leads to fewer bugs (with mutable objects you can forget to take a copy, and any validation is then useless) and fewer copies being made.
Basically, it allows you to reason about your code locally without making copies of everything you either accept and store, or return to other code. When only your code can change the state of your object, it’s much simpler to work out what will happen over time.
Joda Time actually fails somewhat because it has both mutable and immutable types – if you just program to the interface (e.g.
ReadableInstant) then you don’t get those guarantees. That’s why in Noda Time I made all the types genuinely immutable.Out of interest, would you want
Stringto be mutable? If not, try to think about whether there are real differences between the two scenarios.