Open KyleFin opened 1 year ago
- This lint could also suggest annotating class with @immutable. (
consider_const_constructor
lint would be similar toprefer_const_constructors_in_immutables
).
I'd rather go in this direction. I'd prefer an add_immutable_annotation
lint that trigger on classes with only final fields. Thus there would be no overlapping with other lints and it could easily be used together with prefer_const_constructors_in_immutables.
consider_const_constructor
Description
Classes with no non-final fields may benefit from defining a const constructor.
Details
https://dart.dev/guides/language/effective-dart/design#consider-making-your-constructor-const-if-the-class-supports-it
Kind
Suggest potential optimization. Make authors deliberately choose to use const OR ignore lint. Point to useful Effective Dart reference to help them decide.
Bad Examples
Good Examples
Discussion
Background
I came upon this when reviewing some code using bloc. I assumed the default constructor was const and almost suggested removing the const constructor from an event class:
I investigated more and learned that the default constructor is not const. Some resources I came across that helped me better understand why that's the case and when to use or not use const include:
prefer_const_constructors_in_immutables
suggests defining const constructor, prefer_const_constructors suggests using const constructor.Considerations
Should lint just check that at least one const constructor exists? Or that all defined constructors are const?
Square.fromRadius
example above, should making one constructor const satisfy the lint check, or should both constructors be required to be made const (or ignored)?We could have a quick fix to create const constructor (if no constructors are defined) or make an existing constructor const, but it may be better to NOT have a quick fix so authors don't accidentally agree to maintaining a const constructor in their public API.
Is it worth having this lint?
This lint could also suggest annotating class with @immutable. (
consider_const_constructor
lint would be similar toprefer_const_constructors_in_immutables
).Discussion checklist