An algorithm, procedure, or operations is logically const if it does not alter the logical state of an object or type. Note that this is a looser property than PhysicalConstness (the bits don't change). LogicalConstness is useful in several cases:
- LazyEvaluation. Some expressions/objects have state which is difficult or expensive to compute; it is useful to defer evaluation until it is actually needed. Given that most programming languages where const is an issue (those with SideEffects) generally don't have language support for LazyEvaluation, the programmer often has to fake it; and "faking it" almost (?) always involves rearranging the "bits" of the object.
- Caching. If you have a LargeContainer? which is expensive to search, but high locality of reference, caching away the last n searches might be a fruitful optimization. Again, this requires rearranging the bits of the container object.
It is easy for a compiler to determine whether or not the bits change. It is harder to determine whether or not the logical state of an object changes; for this reason implementing
LogicalConst often requires holes be left in the typing system. Two ways to do it are:
- ConstIncorrectness (or CastingAwayConst). Simply discard the ConstQualifier in the implementation of a method which preserves LogicalConstness while rearranging the bits.
- MutableKeyword?. A newer feature in CeePlusPlus language; fields of an object tagged mutable can be updated even in a supposedly const method. (However, there is nothing which prevents the programmer from changing a mutable field in a way which does not preserve LogicalConstness).
A good rule of thumb for
LogicalConst is as follows:
If an operation preserves LogicalConstness, then if the old state and the new state are compared with the EqualityOperator, the result should be true. In other words, the
EqualityOperator should reflect the logical state of the object. I know of no language which enforces this...
-- engineer_scotty (Scott Johnson)
Enforcing logical const in the face of mutable is computationally intractable. You could do some UnitTests, but that is about as far as it can go.
CategoryLogic