LoginSignup
3
2

【Flutter】custom_lint:ifのネストは避けよう

Posted at

こちらは以下の続きになります。

背景

リーダブルコードや良いコード・悪いコードなどあらゆるところで「深いネストは避けよう」と言われることが多いと思います。
Flutterの場合、ウィジェットのネストが深くなるのは場合によって致し方ない&ルール化してしまうと可読性を逆に落とすのでは?と思い、今回はロジックのif文でのネストに注目してルール設定をしました。
if > if >...とネストするのは2重までとし、原則早期returnなどをして欲しいという思いがあります。

実装

import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/error/listener.dart';
import 'package:custom_lint_builder/custom_lint_builder.dart';

class IfNestingLimit extends DartLintRule {
  const IfNestingLimit()
      : super(
          code: _code,
        );

  static const _code = LintCode(
    name: 'if_nesting_limit',
    problemMessage: 'ifのネスト階層は2つまでにしてください',
    errorSeverity: ErrorSeverity.WARNING,
  );

  @override
  void run(
    CustomLintResolver resolver,
    ErrorReporter reporter,
    CustomLintContext context,
  ) {
    context.registry.addIfStatement((node) {
      _checkIfNestingLimit(node, reporter);
    });
  }

  void _checkIfNestingLimit(IfStatement node, ErrorReporter reporter) {
    int nestingLevel = 0;
    AstNode? currentNode = node;

    while (currentNode != null) {
      if (currentNode is IfStatement && currentNode.elseStatement == null) {
        nestingLevel++;
      }
      currentNode = currentNode.parent;
    }

    if (nestingLevel > 2) {
      reporter.reportErrorForNode(_code, node);
    }
  }
}
PluginBase createPlugin() => _MyCustomLinter();

class _MyCustomLinter extends PluginBase {
  @override
  List<LintRule> getLintRules(CustomLintConfigs configs) => [
        // 各lintルールを定義したクラスを配置していく
        const IfNestingLimit(),
      ];
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2