Search code examples
c#invariants

How do you preserve invariants to respect Liskov?


How do you preserve invariants in order to respect Liskov principle (one of SOLID principles)? Could you help me with an example please? I read that class A and class B are invariants if there is no relationship between them (class A is neither a subtype nor a supertype of class B). Is this true? I am confused about what an invariant is.


Solution

  • An invariant is something that holds (or is assumed to hold) all the time.

    The Liskov Substitution Principle states that a proper subtype should not (among other things) invalidate invariants, meaning it should not take a condition that was assumed to be true for all states of the base class and change things so that the condition is now not true for certain states of the object.

    For example, if there is a List<T> class with a Length property of type int and an array of type T[], it may be assumed in all methods of that class that Length is always less than or equal to the length of the internal array. This is an invariant of that class. If a subclass of List<T> makes it so that Length can (under any circumstanes) be greater than the length of the array, then the subclass will have introduced a violation of that invariant.