Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Dart prefer omitting type annotations for local variables?

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?

Why is this:

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

preferable to this:

RegExpMatch match = regexp.firstMatch('Regex Match');
like image 437
joshpetit Avatar asked Aug 31 '25 20:08

joshpetit


1 Answers

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.

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.

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.)

like image 111
lrn Avatar answered Sep 04 '25 18:09

lrn