Sub topic 16
Choosing between extends, implements, with, and composition
This chapter assumes you know how to write classes and constructors in Dart, including super parameters. It also assumes you have seen abstract classes, implicit interfaces, and mixins. Here you decide which relationship to use in a design, and you see what each choice costs later.
The four tools and what each one gives you
Dart offers three keywords for relating one class to another, plus a design technique that uses none of them.
extendsmakes a subclass. You inherit fields, methods, and the superclass's type. You must call a superclass constructor, because constructors are not inherited. A class can have only one superclass.implementspromises to supply every member of another type. You inherit no code and no field storage. A class can implement many types.withmixes in the members of one or more mixins. You inherit code and state, but a mixin has no generative constructor, so it cannot take constructor arguments.- Composition holds another object in a field and forwards calls to it. No language feature is involved.
| Tool | Inherits code | Inherits state | How many | Subtype of the other type | Coupling |
|---|---|---|---|---|---|
| `extends` | Yes | Yes | One | Yes | Highest |
| `implements` | No | No | Many | Yes | Low |
| `with` | Yes | Yes | Many | Yes (the mixin type) | Medium |
| Composition | No (you forward) | No | Any | No | Lowest |
Choosing a relationship
Ask the questions in the diagram in order. Stop at the first "yes".
When you are unsure, choose composition. It is the easiest choice to change later.
extends: a real is-a relationship
Use extends when the subclass is a specialized version of the superclass and should share its state and behavior. A Dog is an Animal, and every Animal has a name.
class Animal {
final String name;
Animal(this.name);
String describe() => 'Animal $name';
}
class Dog extends Animal {
final String breed;
Dog(super.name, this.breed);
@override
String describe() => '${super.describe()} ($breed)';
}
void main() {
print(Dog('Rex', 'Collie').describe());
}The costs are real:
- Fragile base class. If the author of
Animalchanges howdescribeworks, every subclass changes with it, even if you did not touch your code. - One slot. A class can extend only one other class. If you spend it on a convenience, you cannot extend something more important later.
- Constructor coupling. Every subclass constructor must reach a superclass constructor, so a change to the superclass constructor breaks every subclass.
implements: a contract without code
Every class in Dart defines an implicit interface made of its public members. When you write implements, you promise to provide all of them. Nothing is inherited, and that includes fields: a field in the original becomes a getter (and a setter, if it is not final) that you must write yourself.
class Base {
final String name;
Base(this.name);
String greet() => 'Hi $name';
}
class Fake implements Base {
@override
String get name => 'fake';
@override
String greet() => 'fake hi';
}This is useful for test doubles and for hiding an implementation behind a type. It is fragile when the type is a concrete class you do not own. If Base gains a new public method, Fake stops compiling.
For this reason, use a dedicated interface type when you design an API, and use abstract interface class so the intent is clear:
abstract interface class Notifier {
void send(String message);
}Outside its own library, an interface class can be implemented but not extended. Authors of public packages use this to stop consumers from inheriting behavior they never promised to keep stable.
with: a capability for unrelated classes
A mixin is for behavior that does not belong to any one hierarchy, such as logging, change tracking, or a counter. Unrelated classes can share the code without a common superclass.
mixin A {
String who() => 'A';
}
mixin B {
String who() => 'B';
}
class C with A, B {}
void main() {
print(C().who());
}This prints B. When two mixins define the same member, the one listed last wins, because each mixin is applied on top of the previous ones. Dart resolves the order without ambiguity, but readers may not remember it, so avoid overlapping names.
Three more points matter in practice:
- A mixin can hold state. Each instance of the class gets its own copy of the mixin's fields.
- A mixin that needs a particular superclass can declare it with
on, which lets it call superclass members safely. Theonclause also means that only subclasses of that type can use it. - Use
mixin classonly when you really need a type that works both as a mixin and as a superclass. A plainmixincommunicates its purpose better.
Composition: has-a instead of is-a
Composition means a class owns a collaborator and delegates to it. The collaborator is chosen at construction time, so you can swap it at runtime or in tests, and the owner does not inherit anything it does not want.
The next program combines three of the tools. OrderService composes a Notifier, mixes in an audit trail, and tests use a fake that implements the interface.
abstract interface class Notifier {
void send(String message);
}
class ConsoleNotifier implements Notifier {
@override
void send(String message) => print('console: $message');
}
class RecordingNotifier implements Notifier {
final List<String> sent = [];
@override
void send(String message) => sent.add(message);
}
mixin Auditing {
final List<String> auditLog = [];
void audit(String entry) => auditLog.add(entry);
}
class OrderService with Auditing {
OrderService(this._notifier);
final Notifier _notifier;
void place(String item) {
audit('placed $item');
_notifier.send('Order for $item placed');
}
}
void main() {
final fake = RecordingNotifier();
final service = OrderService(fake);
service.place('book');
print(fake.sent);
print(service.auditLog);
}The output is:
[Order for book placed]
[placed book]OrderService does not extend a notifier class, so it inherits nothing it must keep in sync. Replacing RecordingNotifier with ConsoleNotifier requires no change to OrderService. The mixin supplies a small capability that has nothing to do with notifications.
How class modifiers support your choice
Dart 3 modifiers let a library author enforce the relationship you are meant to use.
| Modifier | Effect outside the declaring library |
|---|---|
| `interface` | Can be implemented, not extended |
| `base` | Can be extended or mixed in, not implemented |
| `final` | Cannot be extended or implemented |
| `sealed` | Cannot be extended or implemented, and `switch` over its subtypes must be exhaustive |
If a class is base, you cannot write implements for it. If it is interface, you cannot write extends. When you design your own types, pick the most restrictive modifier that still allows legitimate use. That keeps the options open for you to change internals later.
Common mistakes
- Extending to reuse one method. If you only want a helper, call it through a field, or write a mixin.
- Implementing a concrete class you do not control. New members in a later version will break your code. Implement an interface the author designed for that purpose.
- Mixin order surprises. Check the order in the
withclause when two mixins share a member name. - Deep hierarchies. More than two or three levels usually means some of the layers should be collaborators.
- Forgetting that implements skips constructors and field initializers. An implementing class must provide all state itself.
Exercise
A Report class needs to write its output to either the console or a file, and the choice is made when the program starts. Should Report extend an output class, implement it, mix it in, or hold it in a field? Give the reason.
Show answer
Hold it in a field (composition). The output choice varies at runtime and Report is not a kind of output, so inheritance would be wrong. Define an abstract interface class Output with a write method, give Report a final Output field set through its constructor, and pass either a console or a file implementation.
Exercise
Given mixin Hello { String say() => 'hello'; }, mixin Bye { String say() => 'bye'; }, and class Greeter with Bye, Hello {}, what does Greeter().say() return, and why?
Show answer
It returns hello. When mixins define the same member, the last one in the with clause wins, and Hello is listed last.
Exercise
You maintain a public package and want users to create their own Storage implementations but never subclass your Storage class. Which modifier do you use?
Show answer
interface, as in abstract interface class Storage. Code outside your library can then implement it but cannot extend it.