On using auto in code examples

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Aug 26 22:40:36 PDT 2006


"Georg Wrede" <georg at nospam.org> wrote in message 
news:44ECED66.5070308 at nospam.org...
> I've been doing some programming, as opposed to telling everyone how the 
> language should be. The role change has given me a new angle to the 
> existing documentation.
>
> Using auto in examples shows of course the "ease and flexibility" of the 
> language. But, it does make the examples less efficient for the purpose of 
> teaching the language, or showing quickly and accurately how and what to 
> do!
>
> Of course you save some keystrokes, maybe some time by not having to 
> remember what the exact type is. But in real life, in most cases you have 
> to know the type anyway, unless we're talking about some tight routines 
> where something is defined, used and forgotten -- all within a few lines 
> of code.
>
> I think all examples should use proper types, and then maybe some separate 
> page could explain that here and there you _could_ use auto. And explain 
> also the perils and gotchas of doing so -- which is impossible if auto is 
> spread all over the examples.
>
> Also, having auto all over the place /does/ give the new reader a robust 
> impression that using auto is the Canonical Way of writing D code.

Totally agree - I think auto should only really be used when the type is (1) 
really inconvenient to type out (such as with complex templates) or (2) when 
the type is not entirely obvious or would require considerable juggling 
(such as when _writing_ complex templates).  I've seen

auto x = 5;

And was totally disgusted.  In this case it's actually _longer_ by one 
keystroke.  I'm almost always in the "clearer is better" camp, especially 
after reading through one horrendous open-source project where most of the 
program state was kept in one- and two-letter struct members. 
Fan-effing-tastic.

> Another deceptive thing is the foreach syntax. Even for one who has been 
> here from the start, and who has participated thoroughly in the debate 
> about that particular syntax, seeing the examples makes one stop for a 
> moment and wonder where is this [loop variable] introduced, and what might 
> its type be.

It's just too insidious.

int num;

foreach(num; array)
    writefln(num);

Which num is used?  Since the body of a foreach is really just a fancy 
delegate, and the indices are parameters, you won't even get a name 
shadowing error.  It's not terribly obvious what's happening.  It should 
definitely be:

foreach(auto num; array)
    writefln(num); 





More information about the Digitalmars-d mailing list