Command–query separation principle [re: @mustuse as a function attribute]

H. S. Teoh hsteoh at qfbox.info
Wed Oct 19 19:06:48 UTC 2022


On Wed, Oct 19, 2022 at 06:50:41PM +0000, Paul Backus via Digitalmars-d wrote:
[...]
> The difference between @mustuse and @safe is that adding @safe imposes
> additional restrictions on the *function*, but adding @mustuse imposes
> additional restrictions on the *calling code*.
> 
> Another way to think of it is: @safe is like an "out" contract, and
> @mustuse is like an "in" contract.
> 
> Derived classes are allowed to weaken in contracts and strengthen out
> contracts, but not the reverse. By the same logic, derived classes are
> allowed to remove @mustuse and add @safe, but not the reverse.

Hmm, this actually makes a lot of sense.

If a base class method Base.method has @mustuse but the derived class
method Derived.method doesn't, that's not a problem: callers who hold a
Base reference to the derived instance will respect @mustuse, but
Derived.method doesn't care.  Conversely, you can only cast a Base to
Derived if it's actually an instance of Derived, so calling .method
afterwards without respecting @mustuse doesn't break anything (this does
not allow you to circumvent @mustuse on AnotherDerived.method).

So yes, @mustuse propagates up the class hierarchy, but not necessarily
down.


T

-- 
He who does not appreciate the beauty of language is not worthy to bemoan its flaws.


More information about the Digitalmars-d mailing list