Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

I am new to Dart language. 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? Whenever I create property of class, should I make it private and provide getters/setters? 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. 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?

Dmitry.

Thank you.

like image 628
Dmitry Papka Avatar asked Mar 28 '15 21:03

Dmitry Papka


1 Answers

Thanks for checking out Dart!

No need to encapsulate class fields. Dart creates implicit getters and setters for you. If you need to actually compute something for that field, you can then implement the getter or setter manually. Bonus: this doesn't break consumers of your 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).

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.

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.

Feel free to use type annotations everywhere, it's programmer choice. Anecdote: the dart2js source code uses type annotations pretty much everywhere.

like image 96
Seth Ladd Avatar answered Nov 13 '22 21:11

Seth Ladd