Please do not use 'auto' return types without thoroughly describing the interface

Neia Neutuladh neia at ikeran.org
Tue Dec 26 01:50:06 UTC 2017


On Monday, 25 December 2017 at 22:48:39 UTC, H. S. Teoh wrote:
> The exact type does not and should not need to be known by user 
> code.

It's a public type reported by some of the documentation but not 
other parts. Its capabilities are given vaguely in the docs for 
the functions that return it.

This is a documentation problem, but concrete return types will 
put a hard limit on how bad the documentation situation can be.

> It's an implementation detail.

The fact that there is a named type involved is not shocking. If 
there is not a named type, we can use something like:

   public alias Regex(Char) = typeof(regex([Char.init]));

I can add it in my own code too. Pretty much no chance of 
breakage.

The fact that two functions return values of the same type is 
perhaps an implementation detail, but there's no way to ensure 
you don't break user code that way besides using a unique type 
for each (hello, std.typecons.Typedef). Like I might read the 
docs and, quite reasonably, write:

   auto capture = needFirst ? matchFirst(str, regex) : 
matchAll(str, regex).skip(3).front;
   auto process = asShell ? spawnShell("echo hi") : 
spawnProcess(["/bin/echo", "hi"]);

And that's suddenly going to stop compiling some day. Maybe. 
Except that would be bonkers because nobody's going to write two 
different `Captures` structs to be used in nearly identical 
circumstances. It would be pointless work to have two different 
types with the same interface for processes.

The fact that it's somehow absolutely essential to maintain this 
option in all current cases, but not so essential as to motivate 
anyone to deprecate public types for anything or use Typedef 
everywhere, is kind of worrying.


More information about the Digitalmars-d mailing list