更喜欢省略局部变量的类型注释

更喜欢省略局部变量的类型注释

本文介绍了为什么 Dart 更喜欢省略局部变量的类型注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 dart 已经有一段时间了,只是想知道不进行类型注释的偏好,我个人觉得如果我可以看到类型注释而不想知道某些变量是什么类型,那么更容易理解并返回我的代码是.是否有理由更喜欢 var 而不是直接类型注释?

I've been using dart for some time and just wonder about the preference for not type annotating, I personally find it easier to understand and go back through my code if I can see type annotations and not wonder about what type certain variables are. Is there a reason to prefer var over direct type annotation?

这是为什么:

var match = regexp.firstMatch('Regex Match');

最好是这样:

RegExpMatch match = regexp.firstMatch('Regex Match');

推荐答案

争论点是多余的冗长通常不值得.

The argument is that the extra verbosity is usually not worth it's own weight.

除非您为每个中间值命名,否则您已经在使用无类型表达式没有问题.说:

Unless you name every intermediate value, there are already untyped expressions that you are using without issues. Say:

myThingie.flooTheFloo().biz.baz.fixIt();

这里有四个中间值,您没有为其指定名称和类型,我们通常不认为这是一个问题.如果你把它写成;

Here you have four intermediate values that you haven't given a name and type to, and we don't generally see that as a problem.If you write that out as;

var v1 = myThingie.flooTheFloo();
var v2 = v1.biz;
var v3 = v2.baz;
var v4 = v3.fixIt();

没有什么特别的理由让您突然需要以前不需要的类型.

there is no particular reason that you should suddenly need types that you didn't need before.

可以说,将类型放在变量上不如将类型放在匿名中间结果上重要,因为前者的名称提供了更多信息.如果名称具有足够的描述性,则不应同时需要名称和类型.

Putting types on variables is, arguably, less important than putting types on anonymous intermediate results, because the name of the former provides more information. You shouldn't need both a name and a type if the name is descriptive enough.

然后有人争辩说这些论点都很好,但是您有时无论如何都想为某事赋予一个类型,因为那种情况从上下文中不清楚或名称.没关系,风格指南 只说AVOID";,而不是不要",这意味着可能存在其他原因胜过风格指南推荐的情况.

Some then argue that those arguments are all well and good, but you sometimes want to give a type to something anyway because that one case is not clear from the context or name. And that's OK, the style guide only says "AVOID", not "DON'T", which means that there might be cases where other reasons trump the style guide recommendation.

我个人习惯于编写类型,并且很难不这样做(尤其是 int,它只是在我想都不想之前从我的手指流过!)但是,我尝试在不键入局部变量的情况下编写 Dart 代码,在实践中这没有问题.很多人都有同样的经历.(我想当我在 6 到 12 个月内再次返回该代码时,我们会看到会发生什么.)

I'm personally used to writing types, and it's hard to not do that (especially int, it just flows from my fingers before I can even think about it!)However, I have tried writing Dart code without typing local variables, and in practice it has not been a problem. Lots of people have the same experience. (I guess we'll have see what happens when I go back to that code in 6-12 months again.)

这篇关于为什么 Dart 更喜欢省略局部变量的类型注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:16