What is an invariant? (2023)

matklad.github.io

61 points by SchwKatze 4 days ago


efitz - 10 hours ago

I’m not sure that I agree with the article.

In the course of my work, I think of an invariant as a state that must hold true at all points during the software’s execution.

For example, “port xxx must never accept inbound traffic”.

I don’t think of invariants as mindsets; I think of them as runtime requirements that are observable and testable at any point during execution, and whose violation is an indication that some assumption about state that the proper execution of the software depends on, no longer holds.

Maybe a good analogy would be “a runtime assert”.

driggs - 4 hours ago

I appreciate that the Ada language features baked-in pre- and post-condition invariants as a part of a function's signature. It goes beyond just runtime assertions by becoming a part of the function's contract with callers.

https://learn.adacore.com/courses/intro-to-ada/chapters/cont...

fishstock25 - 4 hours ago

Another way to view such invariant is to see it as a generalization of both pre- as well as post-condition.

The pre-condition is a special case, then the invariant provides the "guard rails" along which the computation proceeds, and then the post-condition is again a special case which ultimately is the result of the computation.

In the search example of the computation, the pre-condition is "the position is somewhere in the allowed indices", the post-condition is "the return value is the position". The stated invariant is "the value is between current min and max bounds". These bounds become tighter and tighter, so that eventually the pre-condition is transformed into the post-condition.

MarkLowenstein - 5 hours ago

Perhaps a nice short summary would be "facts you can rely on". Because the benefit comes from reducing the cognitive load juggled by the programmer. The more possibilities you can eliminate by identifying invariants, the quicker you'll arrive at a working solution.

korasaz - 8 hours ago

[flagged]