On Tuesday, 15 May 2012 at 18:07:12 UTC, Chad J wrote:
An idea I thought of is to introduce a method local declaration that allows a method to access instance-specific-state that isn't accessible to the rest of the class:

This is an interesting idea (as it seems to really try to keep
the state changes internal to the function, which can be seen as
how D handles purity)... however, it breaks the point of purity due to this:

    pure nothrow hash_t toHash() const {
        @instance hash_t bad = 0;
        ++bad;
        return hashfn(field) + bad;
    }

Now it violates everyone's definition of purity and we can no
longer make our sweet optimizations and reasoning about the code.
Sure, we could "trust the programmers to not do this" ... but
that's another debate entirely.

To communicate intents to invalidate the cache:

class Foo
{
        private toStringCacheValid = false;

        public void methodThatInvalidatesCache()
        {
                ...
                toStringCacheValid = false;
        }

        public pure nothrow string toString() const
        {
                // strCache gets stored in an instance of Foo
                // strCache is only accessable in this method body.
                @instance string strCache = null;

                if ( !toStringCacheValid )
                {
                        // Observable change in strCache!
                        // ... because isCaching reveals it
                        //   to everyone.
                        strCache = someComplicatedCalculation();
                        toStringCacheValid = true;
                        return strCache;
                }
                else
                        return strCache;
        }
}

... and setting toStringCacheValid to true in toString violates
const, so this is absolutely not allowed. Sorry.


Maybe there's a solution, but I doubt the solution is something
the programmer can/should do completely transparently.

Reply via email to