site-www
site-www copied to clipboard
'Extension methods' implies "name" is required, but it is not
Page URL: https://dart.dev/guides/language/extension-methods Page source: https://github.com/dart-lang/site-www/tree/master/src/_guides/language/extension-methods.md
Based on this page, it looks like the <name> is required, but based on the specification it is not.
For example, this is legal:
extension on String {
String get first => this[0];
}
void main() {
print('Hello'.first); // H
}
I wonder if this is worth noting, and if it is, if it worth noting if this implicit extension name is public or private (the spec says private, but @munificent and others seem to have thought it was public).
/cc @leafpetersen
iirc, we decided to always show the name because it's usually a bad idea not to include the name (even though that's allowed). @leafpetersen, do you recall?
I don't think it's a particularly bad idea to omit the name - we added that ability for a reason. An extension without a name is private to the library it is defined in and is not visible anywhere else. If you're using library private extensions, most of the time you don't need a name for the extension at all. The only reasons you need a name for a local extension are if 1) you wanted to put a static method on the extension, or 2) you needed to use the name to explicitly call the extension (either to override the default resolution or because the invocation is ambiguous).
In my hazy recollection, the desire to only show the named case might have come from making autocomplete work. Maybe. @filiph do you remember?
Sorry, I can't remember. FWIW, in the video, I start with unnamed extensions, and only mention named extensions at the very end.
@mit-mit might remember. I looked at the PR (#2155) but there's nothing there.
Let's wait until mit gets back from Danish holidays and can weigh in.
Using a name seems more idiomatic to me, but not sure... @munificent is this something the style guide should cover?
Probably at some point, yes. But I don't think we have enough real-world usage to distill what the best practice is yet. Until then, it's reasonable to let people try different styles so we have enough genetic diversity to evolve to the optimal practice.