Dart Analyze

Dart Analyze

Community Analyzer

Don't assign a variable to itself DRT-W1024

Bug risk
Major

DON'T assign a variable to itself. Usually this is a mistake.

BAD:

class C {
  int x;

  C(int x) {
    x = x;
  }
}

GOOD:

class C {
  int x;

  C(int x) : x = x;
}

GOOD:

class C {
  int x;

  C(int x) {
    this.x = x;
  }
}

BAD:

class C {
  int _x = 5;

  int get x => _x;

  set x(int x) {
    _x = x;
    _customUpdateLogic();
  }

  void _customUpdateLogic() {
    print('updated');
  }

  void example() {
    x = x;
  }
}

GOOD:

class C {
  int _x = 5;

  int get x => _x;

  set x(int x) {
    _x = x;
    _customUpdateLogic();
  }

  void _customUpdateLogic() {
    print('updated');
  }

  void example() {
    _customUpdateLogic();
  }
}

BAD:

class C {
  int x = 5;

  void update(C other) {
    this.x = this.x;
  }
}

GOOD:

class C {
  int x = 5;

  void update(C other) {
    this.x = other.x;
  }
}