dart-lang / language

Design of the Dart language
Other
2.67k stars 205 forks source link

Permits clause for sealed types #3067

Open Pante opened 1 year ago

Pante commented 1 year ago

I've been toying around with sealed types and in my opinion they aren't really pleasant to use.

Sealed types require the entire hierarchy to be in the same library. This is fine when there are only a few subclasses or if they are relatively short. However, anything beyond that requires either the entire hierarchy to be in the same file, giving rise to 1k+ lines monstrosities, or split into several files using part '...;' and part of'...' directives. Neither of which are really pleasant. The latter also runs contrary to the advice in https://dart.dev/guides/libraries/create-library-packages#organizing-a-library-package which discourages the use of part '...' and part of '...'.

A real life example where I encountered this was when I was migrating part of my Range library, https://github.com/forus-labs/cauldron/tree/master/sugar/lib/src/core/range. Each subclass really isn't trivial.

I think it'll be really great if a permits clause was introduced, similar to that proposed in https://openjdk.org/jeps/360.

For example:

Range.dart:

import 'package:my_package/all.dart'

sealed class Range permits Interval, Singleton {}

Interval.dart:

final class Interval extends Range {}

Singleton.dart:

final class Singleton extends Range {}
munificent commented 1 year ago

I'm going to re-open this. The fact that the entire sealed hierarchy must be in the same library has come up as an annoying restriction several times already in existing codebases. I don't know if an explicit permits clause is the best solution, but it's not a bad idea.

Pante commented 1 year ago

After sleeping on it, I feel like it isn't exactly requiring sealed types to be in the same library that's annoying. Rather, it is how libraries are declared/work that's annoying. Maybe a better way to declare a library/"scope" will help more?

jakemac53 commented 1 year ago

This could also be another use case for augmentation libraries, given they are generally more sane than part files, but provide the same general affordance of splitting a library across multiple files.