auto in library functions
Jonathan M Davis
jmdavisProg at gmx.com
Sun Dec 23 14:22:47 PST 2012
On Sunday, December 23, 2012 14:16:02 Jonathan M Davis wrote:
> On Sunday, December 23, 2012 23:05:28 Andrej Mitrovic wrote:
> > On 12/23/12, Benjamin Thaut <code at benjamin-thaut.de> wrote:
> > > I just created my first pull request for druntime and there where
> > > multiple commonets to _not_ use auto. I don't quite understand
> > > why it shouldn't be used in library functions. If it should not
> > > be used why is it in the language in the first place?
> > >
> > > Kind Regards
> > > Benjamin Thaut
> >
> > auto is mainly useful for complex return types or for nested types
> > which you can't otherwise declare (called voldemort types), e.g.:
> >
> > auto x = joiner([""], "xyz");
> > writeln(typeid(x)); // => std.algorithm.joiner!(string[],
> > string).joiner.Result
> >
> > When the type is simple you should use the name of the type instead of
> > auto because it serves as useful documentation, especially in library
> > functions where you might later have to fix a bug. It's really useful
> > to know exactly what type each variable is without having to waste
> > time e.g. looking at function declarations to figure out the return
> > type.
>
> Yeah. I don't know what they were complaining about in the pull request, but
> I think that Andrej has it right.
It looks like I misunderstood what was being said here when I said that I
agree with Andrej. I thought that we were talking explicitly about the return
type on a function. I agree that using auto on function return types should be
restricted, but I do _not_ agree that using auto for local variables should be
restricted. Quite the opposite. I think that auto should be used very heavily
for local variables and that explicit types on local variables should only be
used when they're required. It's much easier to refactor code that way and
reduces the risk of code breakage due to type changes.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list