auto: useful, annoying or bad practice?

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Apr 30 21:56:23 UTC 2018


On Mon, Apr 30, 2018 at 09:31:48PM +0000, Giles Bathgate via Digitalmars-d wrote:
[...]
> functions that return auto are a bit odd IMHO, that is a feature
> unique to D. But I don't have a problem with type inference in
> general, all language have it including C#, C++, TypeScript,
> Rust...etc not that that is a good argument, but just that its
> something you have to get used to, because people will use the feature
> whether you like it or not.
[...]

To me, a function that returns auto is basically saying "you should not
need to know, nor should you depend on, the dirty details of the actual
return type".  There's a time and place for that, and I don't recommend
liberally sprinkling auto return types everywhere just for laziness'
sake.  But when it's used, it should be used for improving
encapsulation, by reducing the leakage of implementation details of the
return type, and limiting the calling code to using only agreed-upon
properties (i.e., via documentation, contract, etc.) or introspection
using static if (meaning that your code is explicitly checking for a
certain property before using it, which is a good defensive design, and
presumably will be able to handle the case where said property no longer
holds).

Basically, it's stepping away from the bad old practice of the caller
code digging into the innards of your data types that were never meant
for public use, and consequently you being locked into a particular
implementation because changing said innards will break existing code,
even if existing code isn't using the type "properly"; and stepping into
a better world of more encapsulated and flexible code.  It's stepping
away from that old world of code depending on "undocumented features"
and "hidden calls", to a better world of code that will Just Work(tm)
even if the underlying library changes a return type, and code that can
adapt itself to the return type by using introspection to discover what
is/isn't available without hardcoding anything or making unfounded
assumptions about what the return type has/doesn't have.


T

-- 
Music critic: "That's an imitation fugue!"


More information about the Digitalmars-d mailing list