Declare a variable using var or the type itself?

Asked

Viewed 217 times

0

I started studying Dart and came across this question. In java, it is always used the type in the declaration of a variable. However, Dart allows you to declare both using "var" and the variable type, except for a few exceptions. What would be the most correct/readable form? In my opinion (I am suspicious for already programming in Java), the most correct would be to specify the type of the variable in your statement, since it would specify its function more clearly and readable the code. But if there is this possibility to make statements with "var", something good that I am not seeing should have. From now on, I thank you!

  • "In java, the type is always used in the declaration of a variable." - That’s up to Java 9. In Java 10, you can declare with var. And Ambdas parameters have never needed explicit type declaration (except in a few cases) since they were introduced in Java 8.

  • I understand, I’m off this new update... but what about the question?

1 answer

1


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

That’s up to Java 9. In Java 10, you can declare with var. And Ambdas parameters have never needed 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 something 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 the type String. To illustrate with a more extreme case:

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

It gets simpler 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 most obscure code.

Finally, each case is a case. The use of var can make the code thinner or more obscure. Like any other resource, it is something that should be used with common sense.

  • I get it. So it would be bad practice to always define the type?

  • @Longjohnson updated the answer. Each case is a case.

  • Thank you, I understand perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.