Function attribute best practices
Steven Schveighoffer
schveiguy at gmail.com
Mon Sep 12 18:29:58 UTC 2022
On 9/12/22 1:08 PM, Ali Çehreli wrote:
> On 9/12/22 09:48, H. S. Teoh wrote:
>
> >> @nogc nothrow pure @safe
> >> unittest
> >> {
> >> // ...
> >> }
> >>
> >> No, it isn't because unless my unittest code is impure, I can't catch
> >> my incorrect 'pure' etc. on my member functions.
> > [...]
> >
> > Sure you can. The `pure unittest` code obviously must itself be pure
> > (otherwise it wouldn't compile). If Foo introduces impure behaviour,
> > then the unittest, being pure, wouldn't be allowed to call Foo's impure
> > methods, which is what we want. What's the problem?
>
> There was a problem until you and others put me straigth. :)
>
> What I meant was
>
> - if I put 'pure' etc. on my templatized code,
>
> - and then tested with a 'pure' unittest,
>
> I wouldn't know that the gratuitous use of my 'pure' on the member
> function was wrong. I would be fooling myself thinking that I smartly
> wrote a 'pure' member function and a 'pure' unittest and all worked.
> Wrong idea! :)
So you are thinking about this the wrong way I believe.
When you put `pure` on a template function, you are saying "only
instantiations where this function can be pure are allowed".
Essentially, that's *you* telling your *user* "this must be pure!".
If your intent is to *enforce* pure functions only, then that's what you
do. If your intent instead is to ensure that given proper parameters,
the function will be pure, then the answer is to unittest.
I will say, sometimes this gets really annoying. Like if the unittest
fails, you get very little information about *why* it's not working.
i.e. you expect the inference to be pure, but it's not. All you get is
"impure unittest can't call impure function foo(...)". Figuring out the
misinference cause is a chore today. I wish it would be easier.
-Steve
More information about the Digitalmars-d-learn
mailing list