Why callers should explicitly document storage classes

Lutger Blijdestijn lutger.blijdestijn at gmail.com
Sun Aug 14 05:18:11 PDT 2011


Mehrdad wrote:

> Consider this example:
> 
>      // In module foo.d:
>      void baz(bool condition, lazy int value)
>      {
>          if (condition)
>              writeln(value);
>      }
> 
>      // In module bar.d:
>      import foo;
>      bool someCondition() { return false; }
>      void main()
>      {
>          auto vals = [1, 2, 3, 4];
>          while (!vals.empty)
>              baz(someCondition(), items.moveFront());
>      }
> 
> There is **absolutely NO WAY** to figure out what's wrong at the calling
> site. You need to check /every/ method call and make sure nothing weird
> is happening (e.g. lazy), and it's pretty much impossible to figure it
> out unless you're intimately familiar with the entire library you're
> calling -- something which (obviously) doesn't scale.

I'm not convinced that intimately is the right word here. Lazy evaluation is 
a pretty big deal in the interface of a function, just like ref is. If you 
have no idea at all what a function does, there is no hope to figure out 
what the code at the call site does to begin with. Even without lazy/out/ref 
you could be passing an object with reference semantics to a function which  
mutates the object, same deal. Not everything is 'const correct', so this 
may also be surprising if you do not know the function.

> I don't know of a similar example off the top of my head for out/ref,
> but the same idea applies.
> 
> Is this convincing enough that we need to document storage classes at
> the CALLING site, rather than just the CALLEE site?

Do you mean literally documenting it or having the compiler require you to 
state the storage class? If the first, I'd say it depends on the context. 
The enforce function in phobos for example is clear and well known enough to 
leave it out. I would not want the latter. But yes, if it's not clear enough 
then it's a good idea. Preferably it would be clear from the function name 
and purpose how it operates on the parameters though.


More information about the Digitalmars-d mailing list