Skip to content

Commit

Permalink
Allow magic numbers for default values (#72)
Browse files Browse the repository at this point in the history
* Allow magic numbers for default values

* More tests

---------

Co-authored-by: vladimir-beloded <[email protected]>
  • Loading branch information
solid-vovabeloded and vova-beloded-solid authored Nov 15, 2023
1 parent 1ce6a91 commit eb00fb4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
7 changes: 6 additions & 1 deletion lib/lints/no_magic_number/no_magic_number_rule.dart
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ class NoMagicNumberRule extends SolidLintRule<NoMagicNumberParameters> {
.where(_isNotInsideConstConstructor)
.where(_isNotInDateTime)
.where(_isNotInsideIndexExpression)
.where(_isNotInsideEnumConstantArguments);
.where(_isNotInsideEnumConstantArguments)
.where(_isNotDefaultValue);

for (final magicNumber in magicNumbers) {
reporter.reportErrorForNode(code, magicNumber);
Expand Down Expand Up @@ -122,4 +123,8 @@ class NoMagicNumberRule extends SolidLintRule<NoMagicNumberParameters> {
null;

bool _isNotInsideIndexExpression(Literal l) => l.parent is! IndexExpression;

bool _isNotDefaultValue(Literal literal) {
return literal.thisOrAncestorOfType<DefaultFormalParameter>() == null;
}
}
28 changes: 26 additions & 2 deletions lint_test/no_magic_number_test.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// ignore_for_file: unused_local_variable, prefer_match_file_name
// ignore_for_file: unused_local_variable
// ignore_for_file: prefer_match_file_name
// ignore_for_file: avoid_unused_parameters
// ignore_for_file: no_empty_block

/// Check the `no_magic_number` rule
Expand Down Expand Up @@ -52,6 +55,27 @@ void fun() {
// Allowed in indexed expression
final result = list[1];

// Allowed in DateTime because it doesn't have cons constructor
// Allowed in DateTime because it doesn't have const constructor
final apocalypse = DateTime(2012, 12, 21);
}

// Allowed for defaults in constructors and methods.
class DefaultValues {
final int value;

DefaultValues.named({
this.value = 2,
});

DefaultValues.positional([
this.value = 3,
]);

void methodWithNamedParam({int value = 4}) {}

void methodWithPositionalParam([int value = 5]) {}
}

void topLevelFunctionWithDefaultParam({int value = 6}) {
({int value = 7}) {};
}

0 comments on commit eb00fb4

Please sign in to comment.