Description
The primary constructors proposal now incorporates most of the declaring constructors proposal, which is great. But there's a piece that isn't in primary constructors yet that I think should be: handling private named parameters gracefully.
This subfeature lets you have initialize a private field using a named parameter whose name has the leading _
stripped off. Instead of having to write:
class House {
int? _windows;
int? _bedrooms;
int? _swimmingPools;
House({
int? windows,
int? bedrooms,
int? swimmingPools,
}) : _windows = windows,
_bedrooms = bedrooms,
_swimmingPools = swimmingPools;
}
You can do:
class House({
int? _windows,
int? _bedrooms,
int? _swimmingPools,
});
This solves a problem users have complained about for years (#2509). I think it's important to get this in at the same time as primary constructors, because users are going to really want to use primary constructors as much as they can since they're so much shorter. If we don't handle private named parameters, then if a user wants:
- A primary constructor
- Named constructor parameters
- Encapsulated state
Then they can only pick two. I suspect they'll pick the first two and sacrifice privacy, which goes against good software engineering practices and our recommended guidance. If we strip off the _
automatically and let users have private named parameters, then they can have all three.
The declaring constructors proposal already has, I think, an excellent specification of the behavior (thanks, @lrhn!), so I don't think there's a lot of design work required to take the feature. It's pretty well baked.