How does implicit typing make code clearer?

2019-02-16 17:45发布

In a book I'm reading it states the implicit typing makes the following code clearer than if you didn't use the var keyword:

var words = new[] { "a", "b", null, "d" };

foreach (var item in words)
{
    Console.WriteLine(item);
}

It seems to me that the opposite is true: if you used string instead, then readers of the code would immediately know it was a string in the foreach loop, instead of having to look up in the code where the variable is defined.

How does implicit typing make the above code clearer?

Addendum

The book is C # 3.0 - Die Neuerungen. schnell + kompakt which is in German, the actual text is:

Das Schluesselwort var kann auch beim Durchlaufen von foreach-Schleifen verwendet werden, um somit den Code uebersichtlicher und einfacher zu gestalten. Besonders bei komplexen Typen kann man auf diese Art und Weise Programmierfehler verhindern.

here's my translation:

The var keyword can also be used when iterating through foreach loops, thus making the code easier and simpler to create. Especially when using complex types, this can prevent programming errors.

Ok, reading it more closely now he actually states that var in a foreach loop makes the code easier to create but not necessarily easier to read.

13条回答
相关推荐>>
2楼-- · 2019-02-16 18:02

It's clearer, in the sense of less noise/redundancy. The type of words can be easily deduced by the new[] { ... } statement, both by the compiler and the developer. So var is used in stead of string[], as the latter can visually clutter the code.

It's clearer, in the sense of transparency. You can swap the actual value with an instance of any other type, as long as it's an enumerable type. If you didn't use var, you'd have to change both of the declaration statements in the example.

It's clearer, as it forces you to use good variable names. By using var, you cannot use the type declaration to indicate the contents of the variable, so you'll have to use a descriptive name. You only declare a variable once, but you may use it many times, so it's better to be able to figure out the contents of the variable by it's name. From this perspective, word would have been a better choice for the loop variable name.

Please note that the above reasoning is done from the author's perspective. It doesn't necessarily reflect my personal opinion :)

Edit regarding your addendum:

As I mentioned before, you can swap the underlying collection type, without having to update all your foreach loops. This does make it easier to create and change your code, but doesn't necessarily prevent programming errors. Let's look at both cases after we introduce a Word class as a replacement of the plain strings:

If we don't use the var keyword, the compiler will catch the error:

var words = new[] { new Word("a"), new Word("b"), null, new Word("d") };

// The compiler will complain about the conversion from Word to string,
// unless you have an implicit converion.
foreach (string word in words)
{
    Console.WriteLine(word);
}

If we do use var, the code will compile without errors, but the output of the program will be completely different, if the Word class hasn't (properly) implemented ToString().

var words = new[] { new Word("a"), new Word("b"), null, new Word("d") };

foreach (var word in words)
{
    Console.WriteLine(word); // Output will be different.
}

So, in certain cases subtle bugs can be introduced when you use var, which would have been caught by the compiler otherwise.

查看更多
ら.Afraid
3楼-- · 2019-02-16 18:02

It makes the code clearer when

  1. You have a class with a really long name.
  2. You have linq queries.
查看更多
Rolldiameter
4楼-- · 2019-02-16 18:10

Personally, I'd agree with you. I'm not sure if clearer is the word I would use but in certain situations the var keyword can certainly make it cleaner, i.e:

var myClass = new ExtremelyLongClassNameIWouldntWantToTypeTwice();
查看更多
放荡不羁爱自由
5楼-- · 2019-02-16 18:10

If you wanted to make this code more explicit, I would suggest expanding the new instead of removing var:

var words = new string[] { "a", "b", null, "d" };

Resharper will give you hints to remove redundant code with that example, but you can turn those hints off if you like.

The argument for using var is that in many cases the type identifiers for local variables are redundant, and redundant code should be removed. By removing redundant code, you can make the cases where you do actually care clearer, for example if you want to enforce a specific interface type for a local variable:

ISpecificInterface foo = new YourImplementation()
查看更多
SAY GOODBYE
6楼-- · 2019-02-16 18:10

The primary benefit of explicit typing is in my view that it's possible by just looking at the code what type the variable has. So readability is increased.

And the primary benefits of implicit typing are:

  • Reduces program text in particular for long type names (classes, interfaces) thus improving readibility
  • Causes fewer changes when a return type of a method changes.

It looks as if both options improve readability.

So I guess it depends on your preferences and maybe also on the programming guidelines in your team. With current (refactoring) tool support in IDE's it has become much easier to change type names (a no brainer) so the reason that implicit typing reduces changes has virtually disappeared from an effort perspective.

I'd suggest: Do what works best for you. There is no right or wrong. Try each approach for a while (e.g. by configuring the options of your favorite refactoring tool), then use what makes your life as a developer easier.

查看更多
三岁会撩人
7楼-- · 2019-02-16 18:13

The example is poor, as many examples demonstrating syntactic sugar tend to be - syntactic sugar helps where things are complicated, but nobody likes complicated examples.

There are two cases where you might want to use var, and one where you must:

Where you might want it:

  1. It can be useful in experimental code, when you are switching the types involved quickly while exploring your problem-space.
  2. It can be useful with complicated generic-based types such as IGrouping<int, IEnumerable<IGrouping<Uri, IGrouping<int, string>>>> which can especially happen with intermeditary states within complex queries and enumeration operations.

Personally, I prefer to use even the complicated form over var, as it doesn't cost someone reading it who doesn't care about the exact type (they can just skip it thinking "complicated grouping type"), but is clear to someone who does care without their having to work it out themselves.

Where you need it:

In dealing with anonymous types, in code like:

var res = from item in src select new {item.ID, item.Name};    
foreach(var i in res)    
    doSomething(i.ID, i.Name);

Here res is an IEnumerable or IQueryable of an anonymous type, and i is of that anonymous type. Since the type has no name it's impossible to explicitly declare it.

In this last case, it is not syntactic sugar, but actually vital.

A related gripe, is that SharpDevelop used to have it's own while-editting form of var; one could type:

? words = new string[] { "a", "b", null, "d" };

And at the semi-colon, the editor would produce:

string[] words = new string[] { "a", "b", null, "d" };

Which gave (especially in more complicated cases) the advantage of typing speed along with producing explicit code. They seem to have dropped this now that var does conceptually the same thing, but it's a pity to have lost the typing shortcut to the explicit form.

查看更多
登录 后发表回答