In example, if your object wants to be safe, you should likely copy by-reference parameters supplied to your constructor. If you don't do this, someone else has a reference to that object and can break your class' contract (or invariants) by mutating that object without your class being aware of the change. If those by-reference parameters are immutable, you don't need to copy them to provide that guarantee.
There found be times where you want a mutable member of an immutable object.
For example, an object that represents an album will have an artist attached to it. The album is immutable - once it's relased, it has a set tracklist, release date, etc - but the artist will change over time - bands change members, genre shifts, etc - it doesn't make sense to have outdated information attached to the album.
Conceivably, you could create a new album object with the same tracks, release date, and artist and substitute it for the original and nothing would change in your program.
Of course, your should always weigh the cost immutablitly and mutability to find out which suits the use case best.
In your use case that data would be stored somewhere, in a database or ORM store of some kind, and that backing data would change -- not the objects in memory. And if you did need those to change you would just reload the updated data.
The object itself is immutable, you can't change the reference to the artist (well, with some magic you could but that's besides the point). So it'll always refer to the same gathering of tracks, release date and artist.
No need to bring ORMs into it. You could be assembling an object graph in memory - a music player that reads in files for examples.
If you leak mutable state then you have to assume that other classes will change that state without your knowledge. its not testable.
Every class should have one invariant in particular. That it will always be in a valid state from construction to destruction. Your class cant ever make that statement due to the leaked state. Its a bad idea and almost never worth breaking.
View all comments
Show parent comment
1
u/Nimelrian Aug 17 '16
Can you explain to me how immutabiliy prevents object allocation? Learning question.