When we mutate an object directly, we need to make sure that interested parties are aware of this mutation. E.g. if the todo is displayed in the UI, we need to set up change listeners so that the UI gets notified accordingly.
If we treat objects as immutable, however, then we have eliminated that problem entirely. Since immutable objects cannot be changed after created, the only way to make the UI update is to pass a new updated object to the UI.
Also this makes it easy to track changes. If I kept a previous data,
prevData, and then I received a new data,
- If the data changed, it is guaranteed that
prevData !== nextData. Therefore, there is no need to do defensive copying, since we know that
prevDatacouldn’t mutate in place.
prevData === nextData, then it’s guaranteed that the data is unchanged from the last time, since we know the data couldn’t be mutated in place.
In object-oriented programming, an object is immutable if its state can't be modified after it is created. In Java, a…www.yegor256.com
…which is the context of this article (actually, I stated it in the first paragraph). That’s why I didn’t mention the case of mutating the object at all.
But sure, the fastest way to change an object’s state is to directly mutate it. But you have to be very careful.
I use mutations too, but usually just in a small, isolated place. For larger scale, I prefer to keep things immutable so that I don’t even have to think about unintended mutations.