Skip to content

@protected annotation on methods isn't inherited #53745

@tvolkert

Description

@tvolkert

Situation

Considering the following public API:

class Super {
  /// This is the public API.
  void foo() {
    doFoo();
    print('done');
  }

  /// Subclasses should not call this method directly; instead, call [foo]
  @protected
  @mustCallSuper
  void doFoo() {
    print('doing foo...');
  }
}

class Sub extends Super {
  @override
  void doFoo() {
    super.doFoo();
    print('doing more foo');
  }
}

Problem

The problem here is that the developer of Sub has inadvertently made the doFoo() method public. The analyzer won't warn developers if they do the following in their project:

void main() {
  Sub sub = Sub();
  sub.doFoo();
}

Possible solutions:

Developers don't typically want to open up the visibility of override methods, so one possible solution is just to always inherit the @protected annotation from super methods.

However, maybe it's a valid use case to make a protected method public when overridden? If we choose this to be the case, we could default to inheriting the @protected annotation -- and introduce a @public annotation that explicitly makes a method public again?

Dart info

$ dart info

If providing this information as part of reporting a bug, please review the information
below to ensure it only contains things you're comfortable posting publicly.

#### General info

- Dart 3.3.0-16.0.dev (dev) (Wed Oct 11 21:04:42 2023 -0700) on "macos_arm64"
- on macos / Version 13.6 (Build 22G120)
- locale is en

#### Process info

| Memory |  CPU | Elapsed time | Command line                                                                    |
| -----: | ---: | -----------: | ------------------------------------------------------------------------------- |
|  21 MB | 0.0% |  03-06:48:38 | dart devtools --machine --try-ports 10 --allow-embedding                        |
|  35 MB | 0.0% |     03:40:44 | dart devtools --no-launch-browser                                               |
|  92 MB | 0.0% |  03-06:48:38 | dart language-server --protocol=lsp --client-id=VS-Code --client-version=3.74.0 |

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3A lower priority bug or feature requestarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-warningIssues with the analyzer's Warning codestype-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions