Reputation: 317
I know how to name variables in classes but how does it relate to functions? I've noticed that some devs use final keywords for variables that never change in functions, but the others use var even in functions.
Which of the following examples is recommended in terms of clean code and performance?
doSomething() {
final int i = 1;
print(i.toString());
}
doSomething() {
final i = 1;
print(i.toString());
}
doSomething() {
int i = 1;
print(i.toString());
}
doSomething() {
var i = 1;
print(i.toString());
}
Upvotes: 5
Views: 491
Reputation: 20048
var
or type annotation such as int
?Here's my approach:
In Dart, The var
keyword is used to declare a variable. The Dart compiler automatically knows the type of data based on the assigned variable because Dart is an infer type language.
So, if you know the type before, you can use var
, since Dart can infer the type for you automatically. For example:
var name = 'Andrew'
However, if you don't know the type before, you can use type annotation:
int age;
...
age = 5;
Upvotes: 1
Reputation: 1141
According to the official Dart documentation, using final
vs var
is a matter of taste; the important part is to be consistent. According to this answer, most compilers will notice that a variable is never reassigned whether or not you make it final. The same documentation link says that most variables should not have a datatype explicitly assigned, just the keyword final
or var
. I personally disagree because of bad experiences with accidentally retyping variables, but that is the official recommendation.
If you make the variable final, then the compiler will enforce its status as read-only. The linter recommends that you always use final
for variables that aren't reassigned.
Upvotes: 1
Reputation: 338
It's preferable to use final for values that don't change.
And use linter if you are not sure.
dart pub add lints
- official lints#analysis_options.yaml
include: package:lints/recommended.yaml
dart pub add zekfad_lints
- lints I like to use#analysis_options.yaml
include: package:zekfad_lints/untyped/dart.yaml
# If you are using flutter
#include: package:zekfad_lints/untyped/flutter.yaml
Upvotes: 0