From eb00fb4bb9edbd761b3d6fb6a6a20dead1a52e74 Mon Sep 17 00:00:00 2001 From: solid-vovabeloded <41615621+solid-vovabeloded@users.noreply.github.com> Date: Wed, 15 Nov 2023 18:49:46 +0200 Subject: [PATCH] Allow magic numbers for default values (#72) * Allow magic numbers for default values * More tests --------- Co-authored-by: vladimir-beloded --- .../no_magic_number/no_magic_number_rule.dart | 7 ++++- lint_test/no_magic_number_test.dart | 28 +++++++++++++++++-- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/lib/lints/no_magic_number/no_magic_number_rule.dart b/lib/lints/no_magic_number/no_magic_number_rule.dart index c9e1e201..6f282425 100644 --- a/lib/lints/no_magic_number/no_magic_number_rule.dart +++ b/lib/lints/no_magic_number/no_magic_number_rule.dart @@ -69,7 +69,8 @@ class NoMagicNumberRule extends SolidLintRule { .where(_isNotInsideConstConstructor) .where(_isNotInDateTime) .where(_isNotInsideIndexExpression) - .where(_isNotInsideEnumConstantArguments); + .where(_isNotInsideEnumConstantArguments) + .where(_isNotDefaultValue); for (final magicNumber in magicNumbers) { reporter.reportErrorForNode(code, magicNumber); @@ -122,4 +123,8 @@ class NoMagicNumberRule extends SolidLintRule { null; bool _isNotInsideIndexExpression(Literal l) => l.parent is! IndexExpression; + + bool _isNotDefaultValue(Literal literal) { + return literal.thisOrAncestorOfType() == null; + } } diff --git a/lint_test/no_magic_number_test.dart b/lint_test/no_magic_number_test.dart index b215ec4b..239564a5 100644 --- a/lint_test/no_magic_number_test.dart +++ b/lint_test/no_magic_number_test.dart @@ -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 @@ -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}) {}; +}