Objects Should Be Immutable 🤫
In object-oriented programming, an object is immutable if its state can’t be modified after it is created. 🤞🏻
In Java/C#, a good example of an immutable object is String.✅
Once created, we can’t modify its state. We can request that it creates new strings, but its own state will never change. ❌
However, there are not so many immutable classes in JDK. Take, for example, class Date. It is possible to modify its state using setTime(). 🕒
This is an incomplete list of arguments in favor of immutability ⚡️:
• Immutable objects are simpler to construct, test, and use
• Truly immutable objects are always thread-safe
• They help to avoid temporal coupling
• Their usage is side-effect free (no defensive copies)
• Identity mutability problem is avoided
• They always have failure atomicity
• They are much easier to cache
• They prevent NULL references, which are bad
Let’s discuss the most important arguments one by one. 🌀
https://t.me/pgimg/178
[ Article ] : kutt.it/immtb
〰〰〰〰〰〰
#BestPractices #DesignPatterns
@ProgrammingTip
Post #510
18.5K