On Fri, Sep 27, 2024 at 04:13:45PM -0400, thinkunix via Digitalmars-d-learn 
wrote:
[...]
> I've seen a lot of "use auto everywhere" especially in C++ and was
> wondering where the D community stands on it's use.  Is it generally
> favored or not?
> 
> Personally, I think auto makes understanding code harder for humans.
> But in this example, it seemed like auto was a good fit.

In idiomatic D, you'd use `auto` when either (1) you don't care what the
type is, you just want whatever value you get to be shoved into a
variable, or (2) you *shouldn't* care what the type is, because your
code shouldn't be depending on it, e.g., when you're using Voldemort
types std.algorithm-style.

The reason for (2) is that in UFCS chains, the only thing you really
only care about is what kind of range it is that you're dealing with,
and maybe the element type.  What exactly the container type is, is
unimportant, and in fact, stating it explicitly is detrimental to
maintenance because the library that gave you that type may change the
concrete type in the future while retaining the same range and element
type.  So by naming an explicit type for the range, you introduce a
potential needless breakage in your code when you next upgrade the
library.  Instead, use `auto` to let the compiler figure out what the
concrete type is, as long as it conforms to the expected range semantics
and has a compatible element type, your code will continue to work as
before.

This applies not only to library upgrades, but also to code maintenance,
e.g., if you decide to reshuffle the elements of a UFCS chain to fix a
bug or introduce a new feature.  If explicit types were always used,
every such change would entail finding out and updating the type of
every component in the chain -- for long chains, this quickly becomes
onerous and unmaintainable.  Instead, use `auto` to let the compiler
figure it all out for you, and make your code independent of the
concrete type so that you can simply move things around just by cutting
and pasting, and you don't have to worry about updating every single
referenced type.


T

-- 
How do you solve any equation?  Multiply both sides by zero.

Reply via email to