For OOP, are immutable and invariant synonymous?

I have a vague feeling that a difference exists, but I'm not sure.

I believe that immutable typically is applied to objects, while invariant is typically applied to attributes/values.

In both cases the object or variable would remain unmodified and "true", so they seem to be very similar.

Thanks for any feedback as I am trying to improve the precision of my understanding of these terms, and I think I am overlooking the subtle differences.

有帮助吗?

解决方案

Not sure if those are correct definitions, but for me "immutable" means that a data structure does not change, while an "invariant" is a set condition that does not change and remains true (but it is not related to a specific instance of data).

Now using immutable data structures helps to ensure that invariants remain true, since they don't mutate they will not just suddenly break an invariant that was true before.

其他提示

Immutable refers to an object not changing during it's lifetime.

  • An immutable string. If you concatenate, it creates a new string. The original one is unchanged.

Invariants are guarantees that don't change for a specified duration. They do not have to explicitly exist as attributes or values.

  • Object must be in a valid state at all times.
  • Object must be in state-X to perform operation-Y.
  • If the operation-X is called, the object is guaranteed to be in state-X.
  • Entity can be a Company or a Person, but cannot be both at the same time.
  • A file cannot be both opened and closed at the same time.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top