简体   繁体   English

Dart中有关类成员封装和类型注释的约定是什么?

[英]What are the conventions in Dart about class members' encapsulation and type annotations?

I am new to Dart language. 我是Dart语言的新手。 So I would like to know more about some conventions that programmers follow while developing in this language. 所以我想更多地了解程序员在使用这种语言进行开发时遵循的一些约定。

  1. Should I always encapsulate my class members as I do, for example in Java? 我应该像我一样封装我的类成员,例如在Java中吗? Whenever I create property of class, should I make it private and provide getters/setters? 每当我创建类的属性时,我应该将其设为私有并提供getter / setter吗? Or there are situations when I should leave them public? 或者有些情况我应该公开他们? If so, what are examples of these situations? 如果是这样,这些情况的例子是什么?

  2. In my opinion, type annotations such as String, int, etc. increase readability of code. 在我看来,键入注释,如String,int等,增加了代码的可读性。 They serve as a documentation for other developers who are reading/using my code. 它们作为正在阅读/使用我的代码的其他开发人员的文档。 Programmer should not think value of what type is storing in this variable right now. 程序员现在不应该考虑在这个变量中存储什么类型的值。 So again, what are the situations, that require using var keyword when declaring a variable? 那么,在声明变量时需要使用var关键字的情况又是什么?

Dmitry. 梅德。

Thank you. 谢谢。

Thanks for checking out Dart! 感谢您查看Dart!

No need to encapsulate class fields. 无需封装类字段。 Dart creates implicit getters and setters for you. Dart为您创建隐式getter和setter。 If you need to actually compute something for that field, you can then implement the getter or setter manually. 如果您需要为该字段实际计算某些内容,则可以手动实现getter或setter。 Bonus: this doesn't break consumers of your API. 额外奖励:这不会破坏您的API的消费者。

Example: 例:

class Person {
  int age;
}

Later, you want to calculate age: 之后,您想要计算年龄:

class Person {
  DateTime birthdate;

  int get age => new DateTime.now().difference(birthdate).inDays ~/ 365;
}

In both cases, you can do this: 在这两种情况下,您都可以这样做:

print(person.age);

Pretty cool! 太酷了! No change in API, and no defensive getters and setters (just add them when you need them). API没有变化,也没有防御性的getter和setter(只需在需要时添加它们)。

You should use type annotations for the "surface area" of your code. 您应该为代码的“表面区域”使用类型注释。 For example, use type annotations for method and function signatures. 例如,对方法和函数签名使用类型注释。 For cases where the variable's type is very obvious, you should consider using var , because it's more terse and readable. 对于变量类型非常明显的情况,您应该考虑使用var ,因为它更简洁,更易读。

For example: 例如:

String doCoolStuff(int bar) {
  var clearlyABool = true;
  return 'Hello world';
}

Note that the return type and bar parameter are type annotated, but the clearlyABool uses var because we initialize with a bool . 请注意,返回类型和bar参数是带注释的类型,但clearlyABool使用var因为我们使用bool初始化。

Feel free to use type annotations everywhere, it's programmer choice. 随意使用类型注释,它是程序员的选择。 Anecdote: the dart2js source code uses type annotations pretty much everywhere. 轶事:dart2js源代码几乎无处不在使用类型注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM