Declare a variable using var or the type itself?

-1

I started to study Dart and I came across this questioning. In java, the type is always used in the declaration of a variable. However, Dart allows you to declare both using "var" and variable type, with some exceptions. What would be the most correct / most readable form? In my opinion (I'm suspected of already programming in Java), the most correct would be to already specify the type of variable in your statement, since it would make your function more specified, making the code clearer and readable. But if there is this possibility of making statements with "var", something good that I can not see should have. Thanks in advance!

    
asked by anonymous 30.07.2018 / 00:24

1 answer

1
  

In java, the type is always used in the declaration of a variable.

This is up to Java 9. In Java 10, you can declare with var . And lambda parameters have never needed an explicit type declaration (except in a few cases) since they were introduced in Java 8.

Knowing which is more readable depends a lot and is subjective. It depends on what you want to do with the code. For example:

String x = "abc";
String z = "def";
System.out.println(x + z);

Or:

var x = "abc";
var z = "def";
System.out.println(x + z);

The second is more readable because it is obvious from the context that the variable is of type String . To illustrate with a more extreme case:

Map<String, List<FuncionarioEmpresaDTO>> x = criaUmMapDosFuncionários();
umOutroMétodoQueRecebeOMapDosFuncionários(x);
maisOutroMétodoQueRecebeOMapDosFuncionários(x);

Make it simple with this:

var x = criaUmMapDosFuncionários();
umOutroMétodoQueRecebeOMapDosFuncionários(x);
maisOutroMétodoQueRecebeOMapDosFuncionários(x);

However, this is not always true:

var x = métodoMuitoLoucoQueRetornaTudoOqueVocêImagina();
var y = x.métodoQueVocêNemSabiaQueExistia();
System.out.println(y);

In this case, the use of var left the code more obscure.

Anyway, every case is a case. Using var may make the code leaner or darker. Like any other feature, it is something that should be used with good judgment.

    
30.07.2018 / 00:43