Skip to content

Experimental @sealed annotation #27372

Closed
Closed
@matanlurey

Description

@matanlurey

(I actually wish this was a language feature, but we can start somewhere...)

All over even the Dart SDK codebase I see code like:

/// ...
///
/// May not be subclassed or implemented.
class FooAst {}

There is nothing actually preventing users from doing this.

I've started more aggressively using factory constructors to prevent subclassing:

class DoNotSub {
  factory DoNotSub() => new DoNotSub._sealed();

  DoNotSub._sealed();
}

But this still doesn't prevent implements, which, IMO is a serious problem for:

Data models/structures that are not meant to be mocked:

class Point {
  final int x;
  final int y;

  Point(this.x, this.y)
}

// Should never be necessary... Just use 'new Point'
class MockPoint extends Mock implements Point {}

Classes that implement hashCode and equals comparing private state:

class SnickersBar {
  int _howManyPeanuts;
  bool _includesCaramel;

  SnickersBar();

  @override
  bool operator==(Object o) => 
      o is SnickersBar && 
      o._howManyPeanuts == _howManyPeanuts &&
      o._includesCaramel == _includesCaramel;
}

cc @yjbanov

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2A bug or feature request we're likely to work oncustomer-google3legacy-area-analyzerUse area-devexp instead.type-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