DartIntermediate 2 min read

Dart interfaces and inheritance: swap a delivery service

Depend on a small service contract and choose implements, extends and composition deliberately.

On this page

An application should be testable without sending a real notification. Define the behavior it needs, then provide a concrete adapter or a fake. Inheritance reuses implementation; an interface describes an obligation without requiring that implementation.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
abstract interface class Notifier {
  Future<void> send(String message);
}

class RecordingNotifier implements Notifier {
  final messages = <String>[];
  @override
  Future<void> send(String message) async => messages.add(message);
}

Future<void> completeOrder(Notifier notifier) => notifier.send('Order ready');

Future<void> main() async {
  final fake = RecordingNotifier();
  await completeOrder(fake);
  print(fake.messages.single);
}

Follow the data and control flow

The workflow knows only the interface. The recorder implements the method and captures the observable effect. Dependency injection here is simply passing the dependency as an argument; it does not require a service locator or framework.

Use extends when the subtype genuinely shares the superclass contract and implementation. Use composition when one object owns another service. Overriding a method is a promise to preserve the contract expected by callers, not a license to silently change its meaning.

A mistake to avoid

A subclass that throws for an operation all callers expect to work can violate substitutability. Do not build a deep hierarchy merely to share a helper. Also keep constructor side effects out of a fake: creating the test object should not send a real message.

Practice and verification

Add a notifier that intentionally fails and test the workflow’s response. Then design an email adapter without implementing real delivery. Explain which behavior belongs in the order workflow and which belongs in the adapter.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.