Skip to content
This repository was archived by the owner on Nov 20, 2024. It is now read-only.

Add avoid_var_declarations #3137

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions example/all.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ linter:
- avoid_types_on_closure_parameters
- avoid_unnecessary_containers
- avoid_unused_constructor_parameters
- avoid_var_declarations
- avoid_void_async
- avoid_web_libraries_in_flutter
- await_only_futures
Expand Down
2 changes: 2 additions & 0 deletions lib/src/rules.dart
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import 'rules/avoid_types_as_parameter_names.dart';
import 'rules/avoid_types_on_closure_parameters.dart';
import 'rules/avoid_unnecessary_containers.dart';
import 'rules/avoid_unused_constructor_parameters.dart';
import 'rules/avoid_var_declarations.dart';
import 'rules/avoid_void_async.dart';
import 'rules/avoid_web_libraries_in_flutter.dart';
import 'rules/await_only_futures.dart';
Expand Down Expand Up @@ -256,6 +257,7 @@ void registerLintRules({bool inTestMode = false}) {
..register(AvoidTypesOnClosureParameters())
..register(AvoidUnnecessaryContainers())
..register(AvoidUnusedConstructorParameters())
..register(AvoidVarDeclarations())
..register(AvoidVoidAsync())
..register(AvoidWebLibrariesInFlutter())
..register(AwaitOnlyFutures())
Expand Down
147 changes: 147 additions & 0 deletions lib/src/rules/avoid_var_declarations.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';

import '../analyzer.dart';

const _desc = r'Avoid declaring variables with var.';

const _details = r'''

**DO** declare a variable using its explicit type if it is reassigned, or final,
if it is not.

Declaring a variable using its explicit type is slightly more verbose but
improves readability, adds self-documentation and makes sure that you are not
dependant on compiler-inferred types. Declaring variables as final is good
practice because it helps avoiding accidental reassignments and allows the
compiler to do optimization.

**BAD:**
```dart
class Person {
var name = 'Bella';
var age = 64;
var ageAtBirth = 0;

void celebratesBirthday() => age++;
void addsSecondName(String secondName) => name = '$name $secondName';
}
```

**GOOD:**
```dart
class Person {
String name = 'Bella';
int age = 64;
static const ageAtBirth = 0;

void celebratesBirthday() => age++;
void addsSecondName(String secondName) => name = '$name $secondName';
}
```

**BAD:**
```dart
double foo() {
var x = 20;
x += 3;
var y = x / 3;
return y;
}
```

**GOOD:**
```dart
double foo() {
int x = 20;
x += 3;
final y = x / 3;
return y;
}
```

**BAD:**
```dart
for (var x in [1, 2, 3]) {
print(x);
}
```

**GOOD:**
```dart
for (int x in [1, 2, 3]) {
x = x + x;
print(x);
}
```

**GOOD:**
```dart
for (final x in [1, 2, 3]) {
print(x);
}
```
''';

class AvoidVarDeclarations extends LintRule {
AvoidVarDeclarations()
: super(
name: 'avoid_var_declarations',
description: _desc,
details: _details,
group: Group.style);

@override
List<String> get incompatibleRules =>
const ['unnecessary_final', 'omit_local_variable_types'];

@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this);
registry
..addVariableDeclarationList(this, visitor)
..addDeclaredIdentifier(this, visitor)
..addSimpleFormalParameter(this, visitor);
}
}

class _Visitor extends SimpleAstVisitor<void> {
final LintRule rule;

_Visitor(this.rule);

@override
void visitVariableDeclarationList(VariableDeclarationList node) {
if (!node.isConst &&
!node.isFinal &&
node.keyword != null &&
node.type == null) {
rule.reportLintForToken(node.keyword);
}
}

@override
void visitDeclaredIdentifier(DeclaredIdentifier node) {
if (!node.isConst &&
!node.isFinal &&
node.keyword != null &&
node.type == null) {
rule.reportLintForToken(node.keyword);
}
}

@override
void visitSimpleFormalParameter(SimpleFormalParameter param) {
if (!param.isConst &&
!param.isFinal &&
param.keyword != null &&
param.type == null) {
rule.reportLintForToken(param.keyword);
}
}
}
3 changes: 2 additions & 1 deletion lib/src/rules/omit_local_variable_types.dart
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ class OmitLocalVariableTypes extends LintRule {
group: Group.style);

@override
List<String> get incompatibleRules => const ['always_specify_types'];
List<String> get incompatibleRules =>
const ['always_specify_types', 'avoid_var_declarations'];

@override
void registerNodeProcessors(
Expand Down
7 changes: 5 additions & 2 deletions lib/src/rules/unnecessary_final.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ class UnnecessaryFinal extends LintRule {
group: Group.style);

@override
List<String> get incompatibleRules =>
const ['prefer_final_locals', 'prefer_final_parameters'];
List<String> get incompatibleRules => const [
'prefer_final_locals',
'prefer_final_parameters',
'avoid_var_declarations'
];

@override
void registerNodeProcessors(
Expand Down
93 changes: 93 additions & 0 deletions test_data/rules/avoid_var_declarations.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// test w/ `dart test -N avoid_var_declarations`

const a = 1; // OK
const int b = 1; // OK
final c = 1; // OK
final int d = 1; // OK
int e = 1; // OK
int? f = null; // OK
var g; // LINT
var h = 1; // LINT
var i = null; // LINT
var j = []; // LINT
var k = {}; // LINT
var _; // LINT
var l = int; // LINT
var m = () {}; // LINT
var n = Thing(5); // LINT
late var o; // LINT
late int p; // OK
late int? q; // OK

f1(int i) {} // OK
f2(var i) {} // LINT
f3(int number, var i) {} // LINT
f4({var i}) {} // LINT
f5({required int i}) {} // OK
f6({required var i}) {} // LINT
f7([int? i]) {} // OK
f8([var i]) {} // LINT
f9() {
var i; // LINT
}
f10() {
int? i; // OK
}
f11() {
final i = 'a'; // OK
}

void l1() {
for (var i in [1, 2, 3]) { // LINT
print(i);
}

for (final i in [1, 2, 3]) { // OK
print(i);
}

for (int i in [1, 2, 3]) { // OK
i += 1;
print(i);
}

int j;
for (j in [1, 2, 3]) { // OK
print(j);
}
}

void l2() {
for (var i = 0; i < 3; i++) { // LINT
print(i);
}

for (int i = 0; i < 3; i++) { // OK
print(i);
}
}

void listen(void Function(Object event) onData) {} // OK

f12() {
listen((var _) {}); // LINT
}

class Thing{
Thing(var x) { // LINT
var u; // LINT
listen((var _) {}); // LINT
}
Thing.named({var x}); // LINT

static var a; // LINT
static const b = 'b'; // OK

var j; // LINT
late var k; // LINT
late int i; // OK
}