The question is simple. Can a type that can change its internal state without it being observable from the outside be considered immutable?
Simplified example:
public struct Matrix
{
bool determinantEvaluated;
double determinant;
public double Determinant
{
get //asume thread-safe correctness in implementation of the getter
{
if (!determinantEvaluated)
{
determinant = getDeterminant(this);
determinantEvaluated = true;
}
return determinant;
}
}
}
UPDATE: Clarified the thread-safeness issue, as it was causing distraction.
It depends.
If you are documenting for authors of client code or reasoning as an author of client code, then you are concerned with the interface of the component (that is, its externally observable state and behavior) and not with its implementation details (like the internal representation).
In this sense, a type is immutable even if it caches state, even if it initializes lazily, etc - as long as these mutations aren't observable externally. In other words, a type is immutable if it behaves as immutable when used through its public interface (or its other intended use cases, if any).
Of course, this can be tricky to get right (with mutable internal state, you may need to concern yourself with thread safety, serialization/marshaling behavior, etc). But assuming you do get it right (to the extent you need, at least) there's no reason not to consider such a type immutable.
Obviously, from the point of view of a compiler or an optimizer, such a type is typically not considered immutable (unless the compiler is sufficiently intelligent or has some "help" like hints or prior knowledge of some types) and any optimizations that were intended for immutable types may not be applicable, if this is the case.
Yes, immutable can change its state, providing that the changes are unseen for other components of the software (usually caches). Quite like quantum physics: an event should have an observer to be an event.
In your case a possible implementation is something like that:
public class Matrix {
...
private Lazy<Double> m_Determinant = new Lazy<Double>(() => {
return ... //TODO: Put actual implementation here
});
public Double Determinant {
get {
return m_Determinant.Value;
}
}
}
Note, that Lazy<Double> m_Determinant has a changing state
m_Determinant.IsValueCreated
which is, however, unobservable.
I'm going to quote Clojure author Rich Hickey here:
If a tree falls in the woods, does it make a sound?
If a pure function mutates some local data in order to produce an immutable return value, is that ok?
It is perfectly reasonable to mutate objects that are expose APIs which are immutable to the outside for performance reasons. The important thing about immutable object is their immutability to the outside. Everything that is encapsulated within them is fair game.
In a way in garbage collected languages like C# all objects have some state because of the GC. As a consumer that should not usually concern you.