Composition and delegation
suggest changeComposition means building a class out of other objects that it holds in fields, instead of inheriting from them. Delegation is what the outer object does with those fields: it hands (forwards) some or all of its work to them.
"Favor composition over inheritance" is old advice, and it applies to Dart as much as to Java or C#. Dart gives you several tools that make composition pleasant:
- every class has an implicit interface, so a wrapper can
implementsthe class it wraps abstract interface classdeclares a pure contract- functions are first-class objects, so a behavior can be a field
dart:collectionandpackage:collectionship ready-made forwarding classes (MapView,DelegatingListand friends)- mixins can package up the forwarding boilerplate
- extension types (Dart 3.3+) wrap a value with zero runtime cost and can forward its whole interface with one word
This article covers:
- why extending a concrete class is fragile
- the basic composition pattern
- decorators: stacking wrappers that share an interface
- strategies as function fields, swapped at runtime
- forwarding only part of an API
- built-in forwarding classes for collections
- a reusable forwarding mixin
- extension types as zero-cost delegates
- partial implementations with
noSuchMethod - how to choose between inheritance, mixins and composition
For extends, implements, mixins and class modifiers themselves, see Inheritance.
The problem with extending a concrete class
A subclass depends on the implementation details of its superclass, not just its public API. Here is a simple bag of strings, and a subclass that counts how many items were ever added:
class Bag {
final _items = <String>[];
void add(String item) => _items.add(item);
void addAll(Iterable<String> items) {
for (final item in items) {
add(item);
}
}
int get length => _items.length;
}
class CountingBag extends Bag {
int addCount = 0;
@override
void add(String item) {
addCount++;
super.add(item);
}
@override
void addAll(Iterable<String> items) {
addCount += items.length;
super.addAll(items);
}
}
void main() {
final bag = CountingBag();
bag.addAll(['apple', 'pear', 'plum']);
print('length: ${bag.length}');
print('addCount: ${bag.addCount}');
}
Output:
length: 3
addCount: 6
Three items were added, but the counter says 6. Bag.addAll is implemented by calling add for each item. That's a private detail of Bag, but because CountingBag overrides add, dynamic dispatch routes those internal calls into the subclass, and every item is counted twice.
You could "fix" it by not overriding addAll, but then CountingBag only works as long as Bag.addAll keeps calling add. If a future version of Bag adds items directly to _items, the counter silently breaks. This is known as the fragile base class problem.
Composition: hold the object, forward the calls
Instead of being a Bag, the counting class can have a Bag:
class Bag {
final _items = <String>[];
void add(String item) => _items.add(item);
void addAll(Iterable<String> items) {
for (final item in items) {
add(item);
}
}
int get length => _items.length;
}
class CountingBag {
CountingBag([Bag? bag]) : _bag = bag ?? Bag();
final Bag _bag;
int addCount = 0;
void add(String item) {
addCount++;
_bag.add(item);
}
void addAll(Iterable<String> items) {
addCount += items.length;
_bag.addAll(items);
}
int get length => _bag.length;
}
void main() {
final bag = CountingBag();
bag.addAll(['apple', 'pear', 'plum']);
bag.add('fig');
print('length: ${bag.length}');
print('addCount: ${bag.addCount}');
}
Output:
length: 4
addCount: 4
Now _bag.addAll calls _bag.add, the inner object's own method. The wrapper never sees those internal calls, so it doesn't matter how Bag is implemented.
Other benefits:
- The API is yours.
CountingBagexposes exactlyadd,addAllandlength. IfBaglater gains aclearmethod, it doesn't leak intoCountingBagautomatically. - The delegate can be supplied from outside. The optional constructor parameter lets callers pass an existing
Bag, which is handy in tests. This is the same idea as Dependency injection. - The delegate can be private. Nobody outside can reach
_bagand bypass the counter.
The cost is that CountingBag is no longer a Bag: you can't pass it where a Bag is expected. The fix for that is to share an interface, shown next.
Decorators: wrappers that share an interface
When the wrapper and the wrapped object implement the same interface, callers can't tell them apart, and wrappers can be stacked. This is the decorator pattern.
Declare the contract with abstract interface class so it can only be implemented, not extended. Then write one real implementation and any number of decorators that each take another UserRepository and add one concern:
abstract interface class UserRepository {
Future<String?> find(int id);
Future<void> save(int id, String name);
}
class InMemoryUserRepository implements UserRepository {
final _users = <int, String>{};
@override
Future<String?> find(int id) async {
print(' [db] find $id');
return _users[id];
}
@override
Future<void> save(int id, String name) async {
print(' [db] save $id');
_users[id] = name;
}
}
class CachingUserRepository implements UserRepository {
CachingUserRepository(this._inner);
final UserRepository _inner;
final _cache = <int, String?>{};
@override
Future<String?> find(int id) async {
if (_cache.containsKey(id)) {
print(' [cache] hit $id');
return _cache[id];
}
return _cache[id] = await _inner.find(id);
}
@override
Future<void> save(int id, String name) async {
await _inner.save(id, name);
_cache[id] = name;
}
}
class LoggingUserRepository implements UserRepository {
LoggingUserRepository(this._inner);
final UserRepository _inner;
@override
Future<String?> find(int id) async {
final result = await _inner.find(id);
print('find($id) -> $result');
return result;
}
@override
Future<void> save(int id, String name) {
print('save($id, $name)');
return _inner.save(id, name);
}
}
Future<void> main() async {
final UserRepository repo =
LoggingUserRepository(CachingUserRepository(InMemoryUserRepository()));
await repo.save(1, 'Alice');
await repo.find(1);
await repo.find(2);
await repo.find(2);
}
Output:
save(1, Alice)
[db] save 1
[cache] hit 1
find(1) -> Alice
[db] find 2
find(2) -> null
[cache] hit 2
find(2) -> null
main only sees a UserRepository. Reading the indented lines shows the call travelling through the layers: logging wraps caching, caching wraps the database. The second find(2) never reaches [db], because the cache remembers the null result (it checks containsKey, not just the value).
Each class does one job and can be tested alone, and you can reorder or drop layers in a single place (where the object graph is built) without touching any of them. With inheritance you would need a separate class for every combination: CachingLoggingRepository, LoggingRepository, CachingRepository and so on.
The downside is boilerplate: every decorator must implement every member of the interface, even the ones it simply forwards. For small interfaces this is fine. For large ones, see the forwarding classes and mixins below.
Strategies: behavior as a field
Sometimes the part you want to vary is a single algorithm. In Dart you don't need a class hierarchy for that, a function-typed field is enough:
typedef Discount = double Function(double total);
double noDiscount(double total) => total;
Discount percentOff(double percent) => (total) => total * (1 - percent / 100);
Discount amountOff(double amount) =>
(total) => total > amount ? total - amount : 0;
class Checkout {
Checkout({this.discount = noDiscount});
Discount discount;
final _prices = <double>[];
void scan(double price) => _prices.add(price);
double get total => discount(_prices.fold(0.0, (a, b) => a + b));
}
void main() {
final checkout = Checkout()
..scan(20)
..scan(30);
print(checkout.total);
checkout.discount = percentOff(10);
print(checkout.total);
checkout.discount = amountOff(15);
print(checkout.total);
}
Output:
50.0
45.0
35.0
Checkout delegates the pricing rule to whatever function discount holds. percentOff and amountOff are factories that return closures configured with a value. Because the field isn't final, the strategy can even be swapped while the object is alive, something inheritance can never do: an object's class is fixed for life.
Use a function type when the strategy is one operation. When it needs several related methods or its own state, use an interface with several implementations instead, exactly as in the decorator example.
Forwarding only part of an API
Composition lets you pick which parts of a component become part of your API. Here a Car has an Engine and a Radio, exposes only two of the radio's members, and can replace its engine at runtime:
abstract interface class Engine {
String start();
}
class PetrolEngine implements Engine {
@override
String start() => 'vroom';
}
class ElectricEngine implements Engine {
@override
String start() => '(silence)';
}
class Radio {
String _station = 'off';
void tune(String station) => _station = station;
String get nowPlaying => _station;
void factoryReset() => _station = 'off';
}
class Car {
Car(this._engine);
Engine _engine;
final _radio = Radio();
String start() => _engine.start();
// Forward only the parts of Radio that make sense for a Car.
void tune(String station) => _radio.tune(station);
String get nowPlaying => _radio.nowPlaying;
void replaceEngine(Engine engine) => _engine = engine;
}
void main() {
final car = Car(PetrolEngine());
print(car.start());
car.tune('Jazz FM');
print(car.nowPlaying);
car.replaceEngine(ElectricEngine());
print(car.start());
// car.factoryReset(); // error: not part of Car's API
}
Output:
vroom
Jazz FM
(silence)
If Car extended Radio (a common shortcut when someone wants "the radio methods on the car"), car.factoryReset() would be part of Car's public API, and a Car could be passed anywhere a Radio is accepted. Neither makes sense: a car is not a radio.
A quick test: if you can't honestly say "a Car is a Radio", use a field.
Built-in forwarding classes
Collections have big interfaces: Map has around 30 members and List more than 60. Writing a decorator by hand would be tedious, so the SDK and package:collection provide classes that already forward everything to a wrapped object. You extend them and override only what you want to change.
MapView and friends in dart:collection
MapView<K, V> implements Map<K, V> by forwarding every member to the map passed to its constructor. Here it's used to build a map that creates missing values on demand:
import 'dart:collection';
class DefaultMap<K, V> extends MapView<K, V> {
DefaultMap(this._ifAbsent) : super(<K, V>{});
final V Function(K key) _ifAbsent;
@override
V operator [](Object? key) {
final k = key as K;
return super[k] ?? (this[k] = _ifAbsent(k));
}
}
void main() {
final groups = DefaultMap<String, List<String>>((_) => []);
for (final word in ['apple', 'avocado', 'banana', 'blueberry', 'cherry']) {
groups[word[0]].add(word);
}
print(groups);
print(groups['d']);
print(groups.keys.toList());
final settings = {'theme': 'dark'};
final view = UnmodifiableMapView(settings);
settings['font'] = 'mono';
print(view);
try {
view['theme'] = 'light';
} on UnsupportedError catch (e) {
print(e.message);
}
}
Output:
{a: [apple, avocado], b: [banana, blueberry], c: [cherry]}
[]
[a, b, c, d]
{theme: dark, font: mono}
Cannot modify unmodifiable map
DefaultMap is a real Map<String, List<String>>: print, keys, length and everything else come from MapView and reach the inner map. Only operator [] was changed. Reading groups['d'] inserted an empty list, so d shows up in keys afterwards.
UnmodifiableMapView (and UnmodifiableListView, UnmodifiableSetView) are delegates too: they forward reads to the live map and throw on writes. Note that the view reflects later changes to settings; it's a read-only window, not a copy. See Immutability for when you need a real copy.
DelegatingList and friends in package:collection
package:collection provides DelegatingIterable, DelegatingList, DelegatingSet, DelegatingMap and DelegatingQueue. Add it with dart pub add collection.
Here is the counting example again, this time as a full List:
import 'package:collection/collection.dart';
class CountingList<E> extends DelegatingList<E> {
CountingList(super.base);
int addCount = 0;
@override
void add(E value) {
addCount++;
super.add(value);
}
@override
void addAll(Iterable<E> iterable) {
final items = iterable.toList();
addCount += items.length;
super.addAll(items);
}
}
void main() {
final backing = <int>[];
final list = CountingList(backing);
list.add(1);
list.addAll([2, 3, 4]);
list.insert(0, 0);
print(list);
print('addCount: ${list.addCount}');
print('sum: ${list.sum}');
print('backing: $backing');
}
Output:
[0, 1, 2, 3, 4]
addCount: 4
sum: 10
backing: [0, 1, 2, 3, 4]
Unlike CountingBag extends Bag, this counts correctly: DelegatingList.addAll calls addAll on the wrapped list, not this.add, so there's no double counting. Changes go to the wrapped list, as backing shows, and extension methods for lists such as sum work because CountingList is a List<int>.
It also shows the main caveat of forwarding classes: only overridden members are intercepted. insert added an element without being counted. When a wrapper must enforce a rule (counting, validation, access checks), go through the interface and override every member that can break it.
For streams, dart:async has StreamView, and package:async adds DelegatingStream, DelegatingFuture and DelegatingStreamSubscription.
A reusable forwarding mixin
For your own interfaces you can write the forwarding once, in a mixin, and reuse it in every decorator. The mixin declares an abstract delegate getter and forwards each member to it:
abstract interface class Logger {
void log(String message);
void flush();
}
class ConsoleLogger implements Logger {
@override
void log(String message) => print(message);
@override
void flush() => print('(flushed)');
}
/// Forwards every Logger member to [delegate].
/// Subclasses override only what they want to change.
mixin ForwardingLogger implements Logger {
Logger get delegate;
@override
void log(String message) => delegate.log(message);
@override
void flush() => delegate.flush();
}
class PrefixLogger with ForwardingLogger {
PrefixLogger(this.prefix, this.delegate);
final String prefix;
@override
final Logger delegate;
@override
void log(String message) => super.log('$prefix $message');
}
class FilteringLogger with ForwardingLogger {
FilteringLogger(this.delegate, {required this.minLength});
@override
final Logger delegate;
final int minLength;
@override
void log(String message) {
if (message.length >= minLength) super.log(message);
}
}
void main() {
final Logger logger = FilteringLogger(
PrefixLogger('[app]', ConsoleLogger()),
minLength: 5,
);
logger.log('ok');
logger.log('server started');
logger.flush();
}
Output:
[app] server started
(flushed)
How it works:
ForwardingLoggerimplements everyLoggermember by calling the same member ondelegate.- Each decorator mixes it in, provides
delegatewith afinalfield (a field satisfies an abstract getter), and overrides only the members it cares about. - Inside an override,
super.log(...)calls the mixin's forwarding version, so the message continues down the chain. 'ok'was dropped by the filter.'[app] server started'was let through and prefixed.flushis forwarded untouched by both layers.
When Logger gains a new member, you add one forwarding method to the mixin and every decorator keeps compiling. This is the same structure that DelegatingList uses internally.
Extension types: zero-cost delegates
An extension type (Dart 3.3+) wraps a single value, the representation, in a new static type. At runtime there is no wrapper object at all: the extension type is erased to its representation, so it costs nothing in memory or speed. This makes it a good fit for two delegation patterns:
- Forward everything and add a little:
implements Stringmakes allStringmembers available on the extension type, without writing a single forwarding method. - Forward only what you choose: without
implements, only the members you declare exist.
extension type Email._(String value) implements String {
factory Email(String input) {
final s = input.trim().toLowerCase();
if (!s.contains('@')) throw FormatException('not an email', input);
return Email._(s);
}
String get domain => value.substring(value.indexOf('@') + 1);
}
extension type ReadOnlyList<E>(List<E> _list) {
E operator [](int index) => _list[index];
int get length => _list.length;
Iterable<E> where(bool Function(E) test) => _list.where(test);
}
void sendTo(Email to) => print('sending to $to');
void main() {
final email = Email(' Alice@Example.COM ');
print(email);
print(email.domain);
print(email.length);
print(email.toUpperCase());
sendTo(email);
// sendTo('bob@example.com'); // error: String is not an Email
String plain = email; // OK: Email implements String
print(plain);
final scores = [90, 72, 85];
final view = ReadOnlyList(scores);
print(view[0]);
print(view.length);
print(view.where((s) => s > 80).toList());
// view.add(100); // error: The method 'add' isn't defined for ReadOnlyList<int>
print(view.runtimeType);
print((view as Object) is List<int>);
}
Output:
alice@example.com
example.com
17
ALICE@EXAMPLE.COM
sending to alice@example.com
alice@example.com
90
3
[90, 85]
List<int>
true
Notes:
Emailcan only be created through its factory, because the representation constructorEmail._is private. EveryEmailis therefore trimmed, lowercased and contains@.email.lengthandemail.toUpperCase()come straight fromString, thanks toimplements String. SinceEmailis a subtype ofString, it can be assigned to aStringvariable. The reverse needs the factory.ReadOnlyListexposes only indexing,lengthandwhere. Callingview.add(100)is a compile-time error.- The last two lines show the erasure: at runtime
viewis the originalList<int>. A caller can cast it back and modify it, so extension types are a design tool for clean APIs, not a security boundary. When you must guarantee that nobody can bypass the wrapper, use a real class such asUnmodifiableListView.
An extension type can declare a member with the same name as one of its representation's members, but that only shadows it statically. There's no dynamic dispatch: code that sees the value as a plain String or List calls the original member, and is checks or switch patterns at runtime see only the representation type. When you need real interception, like the counting or caching above, use a class.
Partial implementations with noSuchMethod
If a class declares a noSuchMethod override, Dart lets it implements an interface without providing every member. Calls to the missing members are routed to noSuchMethod with an Invocation describing the call. This is how mocking libraries such as mockito generate fakes, and it's useful for hand-written test doubles that only need a couple of members:
abstract interface class Mailer {
void send(String to, String body);
void sendBulk(List<String> to, String body);
int get queued;
}
// A fake that only implements what the test needs.
class RecordingMailer implements Mailer {
final sent = <String>[];
@override
void send(String to, String body) => sent.add('$to: $body');
@override
dynamic noSuchMethod(Invocation invocation) {
final name = invocation.memberName.toString();
throw UnimplementedError('RecordingMailer does not support $name');
}
}
void main() {
final mailer = RecordingMailer();
mailer.send('bob@example.com', 'hi');
print(mailer.sent);
try {
mailer.sendBulk(['a@example.com'], 'news');
} on UnimplementedError catch (e) {
print(e.message);
}
try {
print(mailer.queued);
} on UnimplementedError catch (e) {
print(e.message);
}
}
Output:
[bob@example.com: hi]
RecordingMailer does not support Symbol("sendBulk")
RecordingMailer does not support Symbol("queued")
Without the noSuchMethod override, the analyzer would report that sendBulk and queued are missing.
Keep this for tests. In production code it hides missing implementations until runtime. Also note that Dart can't generically forward an Invocation to another object (that would need dart:mirrors, which isn't available in Flutter or AOT-compiled programs), so noSuchMethod can't replace a real forwarding class. See Reflection and introspection.
Choosing between inheritance, mixins and composition
| Situation | Use |
|---|---|
| the new class really is a specialized version of the parent, and the parent was designed for subclassing | extends |
several unrelated classes need the same small bundle of code (equality helpers, toJson, logging) |
mixin (with) |
| you need some behavior of another class but aren't one | a private field, forward selected methods |
| you want to add caching, logging, retries or validation around an existing object | decorator: same interface, wrap and forward |
| the varying part is one algorithm | a function-typed field |
| you wrap a collection or stream and change a few members | MapView, DelegatingList, StreamView |
| many decorators of your own interface | a forwarding mixin with an abstract delegate getter |
| a typed wrapper around a value (IDs, emails, units) with no runtime cost | extension type |
| a fake in a test that only needs a few members | implements + noSuchMethod |
Some practical rules:
- Program to interfaces. If decorators are likely, declare an
abstract interface classand have both the real implementation and the wrappersimplementsit. - Keep delegates private and
finalunless swapping them is a feature. - Inject delegates through the constructor so tests can pass fakes.
- When you publish a class that isn't designed for subclassing, mark it
finalorinterface(see Inheritance). That steers users toward composition and leaves you free to change its internals. - Remember that a forwarding wrapper only intercepts the members it overrides. If it enforces an invariant, cover every member that can break it.