Mutable vs immutable objects

前端 未结 12 1573
囚心锁ツ
囚心锁ツ 2020-11-22 09:17

I\'m trying to get my head around mutable vs immutable objects. Using mutable objects gets a lot of bad press (e.g. returning an array of strings from a method) but I\'m hav

12条回答
  •  太阳男子
    2020-11-22 09:36

    Check this blog post: http://www.yegor256.com/2014/06/09/objects-should-be-immutable.html. It explains why immutable objects are better than mutable. In short:

    • 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

提交回复
热议问题