digitalmars.com                        
Last update Sat Oct 7 16:49:27 2023

What is Invariant Good For?

written by Walter Bright

July 31, 2008

Invariant data in a program is data that, once initialized, never changes. A new term was coined for it after discovering that the existing jargon const, final, readonly and immutable had different meanings for different programmers and different programming languages (and even had shifting meanings within programming languages!). A term was needed that enabled a precise definition.

The existing terminology confusion led to the discovery that invariance doesn’t get much respect in the programming language business (*), it’s the Rodney Dangerfield of concepts. C++ only has invariance for literals and top level const. There is, for example, no way to declare a pointer to invariant data. Java has similar problems with its final storage class. There is no way to declare an entire data structure as invariant, or even the leaves of a data structure as invariant. Perl has invariance only for strings.

(Note: pointer to const in C++ does not declare a pointer to invariant data, as another alias to that same data can still change it.)

The D programming language, however, brings invariant to the fore as a transitive, first class, pervasive language feature. Whole data structures can be invariant, as well as leaves and substructures of it. It adds some measure of complexity to the language, and since other languages have such severely limited invariant support, and yet large and successful programs are developed with them, the obvious question is why bother? Invariance doesn’t seem to be a property anyone misses.

So here’s a list, in no particular order of importance, of what invariance is good for and why it is worth the extra complexity:

I believe these add up to a compelling case for invariant support, what do you think?

(*) Functional programming (FP) languages inherently require invariance, but these languages have not really entered mainstream use. Perhaps this is because FP languages take a good thing too far and make everything invariant. FP has sometimes crept in the back door, for example C++ templates were discovered to actually be a functional programming language.

Home | Runtime Library | IDDE Reference | STL | Search | Download | Forums