dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.27k stars 1.58k forks source link

Refactoring operations should use var/final/const as appropriate #50018

Open stevemessick opened 2 years ago

stevemessick commented 2 years ago

Original issue: https://github.com/flutter/flutter-intellij/issues/6304

Summary: refactoring operations that create new declarations should use final and const where appropriate. Currently, var is used everywhere.

bwilkerson commented 2 years ago

It seems like the Dart analyzer ought to be able to determine that a declaration should be var if its redefined, final it is isn't, and const if it is a constant (not sure about that last).

I wish it were that simple. The problem, of course, is that the variable didn't exist before the extract operation, so it's guaranteed that it isn't re-assigned yet. What we can't know is whether the user will assign a new value after this operation.

The point about const is interesting. If the original expression is a const expression, then perhaps we should use const for it. (It isn't guaranteed that that's the right thing either, but it is an interesting signal.)

That said, the original point is valid and something we have been discussing. The question is, what signals can we use to determine the user's preferences? One signal that comes to mind is style-based lints that have been enabled. In this case, it seems clear that if the user has enabled prefer_final_locals then they probably want the variable to be declared using final. The question is whether that's sufficient.

asashour commented 2 years ago

Duplicate of #49561, but this has feedback.