As per this link
Seeing as rule #1 is horrible, I would caution against taking the rest of the blog post as law. Though really, no blog post should be taken as law.
And the quote itself is rather contradictory:
- A good object should never change his encapsulated state.
- Be aware that immutability doesn't mean that all methods always return the same values.
Here's the thing, if you have immutable state, and your methods return different values then at least one of two things are true:
- Your function varies based on its inputs.
- Your function has side effects (works with something that does have mutable state).
(The example in the article hits on #2.)
The second of these conditions defeats the purpose of having immutable objects, and making that distinction between "encapsulated state" and other state is facetious at worst, impractical at best.
And the first of these conditions is good. Functions should only vary on their inputs where possible. Hiding the immutable state in the class harms that a little bit on the clarity front, but varies greatly on what you're actually doing.
Anyways, on to your question:
Without performance overheads, can such implementations(class LinkedList) be introduced by instantiating as immutable objects?
It depends on your language/implementation. Linked lists lend themselves fairly well to immutable construction because the innards of each "link" aren't really mutable. It's relatively easy to make new links with new pointers.
In Java, I doubt you could do such things without some overhead due to the hit to the garbage collector. You can't even do object pooling since there's no way to reuse the immutable objects reliably. And you certainly couldn't do it while maintaining the existing Java interfaces, which are designed with mutability (and maintaining a reference to the list) in mind.
Does a good object never change its state?
Such an absolute is not correct. Yes, immutability provides a number of benefits. Yes, you should probably default to making your objects immutable in Java and many other languages. But there are many perfectly good objects that change their state, and not a few objects (collections especially) where the mutable object is far better (more usable, more robust, more performant, more flexible, more maintainable) than an immutable design.