Вопрос

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