Mutable vs immutable objects

前端 未结 12 1710
囚心锁ツ
囚心锁ツ 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:54

    Immutable objects are a very powerful concept. They take away a lot of the burden of trying to keep objects/variables consistent for all clients.

    You can use them for low level, non-polymorphic objects - like a CPoint class - that are used mostly with value semantics.

    Or you can use them for high level, polymorphic interfaces - like an IFunction representing a mathematical function - that is used exclusively with object semantics.

    Greatest advantage: immutability + object semantics + smart pointers make object ownership a non-issue, all clients of the object have their own private copy by default. Implicitly this also means deterministic behavior in the presence of concurrency.

    Disadvantage: when used with objects containing lots of data, memory consumption can become an issue. A solution to this could be to keep operations on an object symbolic and do a lazy evaluation. However, this can then lead to chains of symbolic calculations, that may negatively influence performance if the interface is not designed to accommodate symbolic operations. Something to definitely avoid in this case is returning huge chunks of memory from a method. In combination with chained symbolic operations, this could lead to massive memory consumption and performance degradation.

    So immutable objects are definitely my primary way of thinking about object-oriented design, but they are not a dogma. They solve a lot of problems for clients of objects, but also create many, especially for the implementers.

提交回复
热议问题