Search code examples
oopimmutabilityinvariants

For OOP, are immutable and invariant synonymous?


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.


Solution

  • 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.