Sub topic 16
Choosing Between `extends`, `implements`, `with`, and Composition
Assume you know basic Dart syntax, null safety, classes, and methods. This chapter focuses on design choices rather than syntax alone.
Dart provides four ways to relate classes:
extendscreates a subclass that inherits implementation from one superclass.implementsfollows a type contract without inheriting its implementation.withadds a mixin's behavior to a class.- Composition gives a class another object and delegates work to it.
Compare the choices
| Choice | Main relationship | Reuses implementation? | Best when |
|---|---|---|---|
| `extends` | Is-a subtype | Yes | The subclass truly specializes its superclass |
| `implements` | Promises the same API | No | You need interchangeable implementations |
| `with` | Adds a capability | Yes | Behavior can be reused independently |
| Composition | Has-a collaborator | Through delegation | You want flexible, replaceable parts |
Use `extends` for a true subtype
A subclass should be usable anywhere its superclass is expected. It inherits fields and methods, and it can override behavior.
class Notification {
String format() => 'A notification';
}
class EmailNotification extends Notification {
@override
String format() => 'An email notification';
}
void main() {
final Notification message = EmailNotification();
print(message.format());
}EmailNotification is a Notification, so extends expresses the relationship clearly. Avoid extending a class only to reuse one convenient method. Changes in the superclass can then unexpectedly affect the subclass. This is often called the fragile base class problem.
Use `implements` for a contract
A class that uses implements must provide every instance member in the contract. It does not receive the contract's method bodies.
abstract interface class Formatter {
String format(String value);
}
class UppercaseFormatter implements Formatter {
@override
String format(String value) => value.toUpperCase();
}
void main() {
final Formatter formatter = UppercaseFormatter();
print(formatter.format('hello'));
}Use this when callers need one stable type but implementations may work differently. The trade-off is repetition: adding a member to the interface requires every implementation to update.
Use `with` for reusable capabilities
A mixin adds behavior without creating another superclass hierarchy. A class can extend one superclass and apply multiple mixins.
mixin Timestamped {
DateTime get createdAt => DateTime.now();
}
class Event with Timestamped {
final String name;
Event(this.name);
}
void main() {
final event = Event('started');
print('${event.name} at ${event.createdAt}');
}Use a mixin for a capability such as logging, caching, or serialization. A mixin should not silently depend on unrelated fields. If it needs a particular superclass, restrict it with mixin Name on BaseClass.
Use composition for replaceable parts
Composition means storing another object in a field. It keeps dependencies explicit and makes testing easier.
abstract interface class Sender {
void send(String message);
}
class ConsoleSender implements Sender {
@override
void send(String message) => print(message);
}
class AlertService {
final Sender sender;
AlertService(this.sender);
void alert(String message) => sender.send('ALERT: $message');
}
void main() {
final service = AlertService(ConsoleSender());
service.alert('Disk space is low');
}AlertService does not become a Sender. It has a Sender. You can pass a test sender later without changing AlertService.
A practical decision path
When two choices seem possible, choose the one with fewer hidden dependencies. Composition usually gives the most flexibility. Inheritance can be clearer when the domain relationship is strong and stable.
Exercise
A CsvParser needs a Logger, but it is not a kind of logger. Which relationship should you use, and why?
Show answer
Use composition. Store a Logger field and pass it into CsvParser, because the parser has a logger rather than being a logger.