auto: useful, annoying or bad practice?

I love Ice Cream IloveIcecream. at icecreamsandwhich.com
Sun May 20 00:44:13 UTC 2018


'auto' in the sense that C# and other languages use 'var' makes 
perfect sense. There is nothing wrong with it and it takes out 
redundant 'noise':

     var i = "This is a string"; // don't need to know two times 
that this is a string.
     var j = SomethingThatReturns(); // IDE or function docs will 
have my back here...

FYI, I wouldn't use this for 'time saving'. It's to take out 
redundant noise, which can clutter code. It also enables easy 
switching of return types from methods which occasionally means 
you don't have to change any code. It is frequent the type you 
change it to might follow the same protocol/interface as the 
previous type. Or you are just not using anything special with 
the type (maybe just forwarding a return). I do a ton of C# code 
and it's common with the .NET framework that this happens (for 
instance when working with collections). In short 'auto' or 'var' 
is not for time saving. It's to increase code readability and 
code refactorability. Those are it's benefits worth a damn.

Most people spend more time reading code than writing code so if 
you are worried about the time it takes to type out 'auto' vs. 
'SomeObnoxiouslyLongAndOverlyVerboseTypeName' then I think you 
are turning an anthill into a mountain. It's one thing when a 
language feature takes away the need to write hundreds of lines 
of common boiler plate code, but when it just prevents you from 
typing out a really long name? Come on...please...that's not why 
'auto'/'var' has gained industry recognition. There's just a lot 
of people that use it because it's an idiom without taking the 
time to understanding why it _is_ an idiom. So they say things 
like 'I type less, so I like it'.

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.





More information about the Digitalmars-d mailing list