auto: useful, annoying or bad practice?

Neia Neutuladh neia at ikeran.org
Sun May 20 02:34:38 UTC 2018


On Sunday, 20 May 2018 at 00:44:13 UTC, I love Ice Cream wrote:
> Which brings me to where it probably is not a good place for 
> it...in the return fadeclaration of a function/method. I'm very 
> close to saying, even after having read some of the comments 
> that try justifying it, that 100% of the time you want to 
> specify the return type. When you create a function that 
> returns something, you are actively deciding 'I need to return 
> this thing, this is useful or the point of this function'. To 
> not have that thing obviously spelled out in the API is a huge 
> design mistake. Not only do you take away a self-documenting 
> part of you function definition, you make someone have to 
> either have a good IDE (which some people are adverse to using) 
> or actually go read the source code. To not put the effort into 
> thinking about the type (or constraints on the type when 
> dealing with generic/templated code) is just lazy. And worse, 
> it will facilitate libraries where people didn't think about 
> their API as much as they should.

The return type for range-oriented functions in std.algorithm is 
usually not terribly useful. You get a range whose capabilities 
depend on the type of range you pass in, so you have to read the 
source code in any case. But at least listing the actual return 
type lets you skip some reading.

This design by introspection stuff is powerful, but it's 
unfriendly toward people trying to understand your code.

D is very hard to make an IDE for that would actually tell you 
what type the return value is. `pragma(msg, typeof(foo))` is 
probably your best bet, and that's kind of terrible.

Oh, there's also one other use of `auto` return types that I 
haven't seen mentioned before: it functions as a DMD pragma to 
include the function in generated .di files. Wretched, no?


More information about the Digitalmars-d mailing list