隐式键入如何使代码更清晰? [英] How does implicit typing make code clearer?

查看:79
本文介绍了隐式键入如何使代码更清晰?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在阅读的书中,与没有使用var关键字的情况相比,隐式键入使以下代码更清晰:

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);
}

在我看来,情况恰恰相反:如果使用string代替,则代码阅读者将立即知道它是foreach循环中的字符串,而不必在代码中查找变量所在的位置已定义.

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.

隐式键入如何使上面的代码更清晰?

这本书是 C#3.0-Die Neuerungen . schnell + kompakt (德语),实际文本为:

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

《 Durchlaufen von foreach-Schleifen verwendet werden》和《密码保护法》.卑鄙的混血儿,艺术与微调计划的执行者.

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.

这是我的翻译:

在遍历foreach循环时,也可以使用var关键字,从而使代码更易于创建.尤其是在使用复杂类型时,这可以防止编程错误.

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.

好吧,现在更仔细地阅读它,实际上他说在foreach循环中var使代码更易于创建,但不一定易于阅读.

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.

推荐答案

我认为奇怪的是,只有C#和Java程序员似乎受苦于阻止他们从代码上下文中提取信息,而Python的开发者, JavaScript,Ruby,F#,Haskell和其他似乎不受此影响.为什么它们看起来表现不错,但我们的C#程序员需要进行此讨论?

I think it's odd that only C# and Java programmers seem to suffer from an affliction that prevents them from extracting information from the context of code, while developers of Python, JavaScript, Ruby, F#, Haskell and others seem to be immune to this. Why is it that they appear to be doing fine, but us C# programmers need to have this discussion?

如果上述显式类型声明是草率的或懒惰的,这是否意味着没有高质量,可读的Python代码?实际上,难道没有人赞扬Python具有可读性吗?关于JavaScript中的动态类型,有很多让我感到烦恼的事情,但是缺少显式类型声明并不是其中之一.

If foregoing explicit type declarations is sloppy or lazy, does that mean there's no high quality, readable Python code? In fact, don't many people praise Python for being readable? And there are many things that irk me about dynamic typing in JavaScript, but lack of explicit type declarations isn't one of them.

静态类型语言中的类型推断应该是规范,而不是例外.它减少了视觉上的混乱和冗余,同时当您明确指定类型时明确意图,因为您想要一个较少派生的类型(IList<int> list = new List<int>();).

Type inference in statically typed languages should be the norm, not the exception; it reduces visual clutter and reduncancy, while making your intention clearer when you do specify a type explicitly because you want a less derived type (IList<int> list = new List<int>();).

有些人可能会这样反对var:

Some might argue a case against var like this:

var c = SomeMethod();

好吧,我想说的是,您应该给变量赋予更合理的名称.

Well, to that I'd say you should give your variables more sensible names.

已改进:

var customer = SomeMethod();

更好:

var customer = GetCustomer();

让我们尝试显式键入:

Customer customer = GetCustomer();

您现在拥有以前没有的哪些信息?现在您可以确定它的类型为Customer,但是您已经知道了,对吗?如果您已经熟悉该代码,那么就知道通过变量名可以在customer上期望使用什么方法和属性.如果您还不熟悉代码,则不知道Customer有什么方法.这里的显式类型没有增加任何价值.

What information do you now have that you did not have before? You now know for certain it's of type Customer, but you already knew that, right? If you're familiar already with the code, you know what methods and properties you can expect on customer, just by the name of the variable. If you're not familiar with the code yet, you don't know what methods Customer has any way. The explicit type here added nothing of value.

也许var的一些反对者可能会承认,在上面的示例中,var没有害处.但是,如果方法不返回简单且众所周知的类型(如CustomerOrder),但返回某些经过处理的值(如某种字典)怎么办?像这样:

Perhaps some opponents of var might concede that in the above example, var does no harm. But what if a method doesn't return a simple and well-known type like Customer, or Order, but some processed value, like some sort of Dictionary? Something like:

var ordersPerCustomer = GetOrdersPerCustomer();

我不知道返回的内容可能是字典,列表,数组或其他任何东西.但这有关系吗?从代码中,我可以推断出我将拥有一个可迭代的客户集合,其中每个Customer依次包含一个可迭代的Order集合. 我真的不在乎这里的类型.我知道我需要知道的,如果事实证明我错了,那是用名称误导我的方法的错误,无法通过显式类型声明进行修复.

I don't know what that returns, could be a dictionary, a list, an array, anything really. But does it matter? From the code, I can infer that I'll have an iterable collection of customers, where each Customer in turn contains an iterable collection of Order. I really don't care about the type here. I know what I need to know, if it turns out I'm wrong, it's the fault of the method for misleading me with its name, something which cannot be fixed by an explicit type declaration.

让我们看一下显式版本:

Lets look at the explicit version:

IEnumerable<IGrouping<Customer,Order>> ordersPerCustomer = GetOrdersPerCustomer();

我不了解您,但是我发现从中提取所需信息变得更加困难.这至少是因为包含实际信息(变量名)的位在右侧,这让我的眼睛需要更长的时间才能找到它,在视觉上被所有那些疯狂的<>遮盖住了.实际的类型毫无价值,这是个傻瓜,特别是因为要理解它,您需要知道这些泛型的作用.

I don't know about you, but I find it much harder to extract the information I need from this. Not in the least because the bit that contains the actual information (the variable name) is further to the right, where it will take my eyes longer to find it, visually obscured by all those crazy < and >. The actual type is worthless, it's gobbledygook, especially because to make sense of it, you need to know what those generic types do.

如果只是从名称上不确定任何方法做什么或包含什么变量,则应给它起一个更好的名称.这比看它是什么类型更有价值.

If at any point you're not sure what a method does, or what variable contains, just from the name, you should give it a better name. That's way more valuable than seeing what type it is.

不需要 显式键入,如果是,则您的代码有问题,而不是类型推断. 不需要,因为其他语言显然也不需要.

Explicit typing should not be needed, if it is, there's something wrong with your code, not with type inference. It can't be needed, as other languages apparently don't need it either.

也就是说,我确实倾向于对原语"使用显式键入,例如intstring.但老实说,这更多是习惯,而不是有意识的决定.尽管使用数字,但是如果忘记了将m添加到要键入为decimal的文字数字上,类型推断可以使您感到困惑,这很容易做到,但是编译器不允许您这样做.意外失去精度,所以这不是实际问题.实际上,如果我在任何地方都使用var,它将大大简化我在从整数到十进制数的大型应用程序中的数量更改.

That said, I do tend to use explicit typing for 'primitives', like int and string. But honestly, that's more a thing of habit, not a conscious decision. With numbers though, the type inference can screw you if you forget to add the m to a literal number that you want to be typed as decimal, which is easy enough to do, but the compiler won't allow you to accidentally lose precision so it's not an actual problem. In fact, had I used var everywhere it would've made a change of quantities in an large application I work on from integers to decimal numbers a lot easier.

var的另一个优点是:它允许快速实验,而不会强迫您在任何地方更新类型以反映您的更改.如果我想将上面的示例更改为Dictionary<Customer,Order>[],则只需更改我的实现,用var调用它的所有代码将继续起作用(嗯,至少是变量声明).

Which is another advantage of var: it allows rapid experimentation, without forcing you to update the types everywhere to reflect your change. If I want to change the above example to Dictionary<Customer,Order>[], I can simply change my implementation and all code that called it with var will continue to work (well, the variable declarations at least).

这篇关于隐式键入如何使代码更清晰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆