site-www icon indicating copy to clipboard operation
site-www copied to clipboard

'Extension methods' implies "name" is required, but it is not

Open matanlurey opened this issue 5 years ago • 7 comments

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

matanlurey avatar Apr 07 '20 23:04 matanlurey

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?

kwalrath avatar Apr 08 '20 00:04 kwalrath

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).

leafpetersen avatar Apr 08 '20 01:04 leafpetersen

In my hazy recollection, the desire to only show the named case might have come from making autocomplete work. Maybe. @filiph do you remember?

kwalrath avatar Apr 08 '20 17:04 kwalrath

Sorry, I can't remember. FWIW, in the video, I start with unnamed extensions, and only mention named extensions at the very end.

filiph avatar Apr 08 '20 21:04 filiph

@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.

kwalrath avatar Apr 08 '20 21:04 kwalrath

Using a name seems more idiomatic to me, but not sure... @munificent is this something the style guide should cover?

mit-mit avatar Apr 14 '20 13:04 mit-mit

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.

munificent avatar Apr 20 '20 23:04 munificent