Sub topic 3
Depending on abstractions, not implementations
This chapter assumes you can write Dart classes, abstract classes, and implements clauses, and that you know async/await and ChangeNotifier. It builds on constructor injection from the previous chapter. Passing a dependency in is only half of the decoupling. The other half is the type you declare for it.
Why the parameter type matters
Constructor injection removes the new call from the class that uses a dependency. If the constructor parameter is still a concrete class, the coupling is still there:
import 'package:flutter/foundation.dart';
class ApiUserRepository {
Future<String> fetchName(int id) async {
// Calls the real backend.
return 'User $id';
}
}
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final ApiUserRepository _repository; // still a concrete type
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
notifyListeners();
}
}The caller supplies the object, but it can only supply an ApiUserRepository or a subclass of it. To test this view model, you must either subclass the real repository, which runs its real constructor and fields, or stand up a fake server. To switch to a cached repository, you must edit ProfileViewModel.
The fix is to make the view model depend on a type that describes what it needs, not how that need is met.
Defining the abstraction
An abstraction in Dart is an abstract class (or an interface class) that declares members without implementing them. It is the contract between the consumer and the provider.
abstract class UserRepository {
Future<String> fetchName(int id);
}Both sides now depend on this type, and neither depends on the other:
ProfileViewModeldeclaresfinal UserRepository _repository;.ApiUserRepositorydeclaresimplements UserRepository.
This is the "D" in the SOLID principles: high-level code (the view model) and low-level code (HTTP, databases) both depend on an abstraction owned by the high-level side. The contract is shaped by what the view model needs, not by what the backend happens to offer.
`implements` versus `extends`
Dart has no separate interface keyword in older code. Every class defines an implicit interface, and you use it with implements. The choice between implements and extends matters:
| Keyword | What you get | Typical use |
|---|---|---|
| `implements` | Only the signatures. You must override every member, including fields as getters. No constructor or method body is inherited. | Real implementations and fakes of a contract |
| `extends` | Inherited fields, constructors, and method bodies. | Sharing real code between related implementations |
For fakes, prefer implements. A fake that extends the real repository runs the real constructor and inherits real behavior for any method you forget to override. A fake that implements the contract cannot compile until you cover every member, so a new method in the contract surfaces every fake that needs updating.
Since Dart 3 you can state the intent in the declaration:
abstract interface class UserRepository {
Future<String> fetchName(int id);
}An interface class can be implemented outside its library but not extended. That forces consumers to treat it as a pure contract. If you do not want that restriction, plain abstract class (as used in the spine of this tutorial) works fine.
What belongs in the contract
The contract is only useful if it contains no hints about the implementation. Two things commonly leak.
Types from the implementation's library. If fetchName returned an http.Response or a Dio Response, every consumer would need that package, and every alternative implementation would have to fake an HTTP response. Return your own types or plain Dart values.
Implementation-specific errors. If the view model catches DioException or SocketException, swapping the implementation breaks error handling. The implementation should translate failures into exceptions the contract defines.
import 'dart:convert';
import 'package:http/http.dart' as http;
class UserNotFoundException implements Exception {
const UserNotFoundException(this.id);
final int id;
@override
String toString() => 'UserNotFoundException: no user with id $id';
}
abstract class UserRepository {
/// Returns the user's display name.
///
/// Throws [UserNotFoundException] when no user has [id].
Future<String> fetchName(int id);
}
class HttpUserRepository implements UserRepository {
HttpUserRepository(this._client, this._baseUrl);
final http.Client _client;
final Uri _baseUrl;
@override
Future<String> fetchName(int id) async {
final response = await _client.get(_baseUrl.resolve('users/$id'));
if (response.statusCode == 404) {
throw UserNotFoundException(id);
}
if (response.statusCode != 200) {
throw StateError('Unexpected status ${response.statusCode}');
}
final json = jsonDecode(response.body) as Map<String, dynamic>;
return json['name'] as String;
}
}The doc comment on fetchName is part of the contract. It tells every implementer, including test fakes, which failure the caller expects. A view model can now handle UserNotFoundException without knowing whether the data came from HTTP, SQLite, or memory.
class FakeUserRepository implements UserRepository {
FakeUserRepository({this.knownIds = const {1}});
final Set<int> knownIds;
@override
Future<String> fetchName(int id) async {
if (!knownIds.contains(id)) throw UserNotFoundException(id);
return 'Test User';
}
}This fake supports the not-found path with no network and no mocking library.
Keeping contracts small
A contract with twenty methods is hard to fake and tempts every consumer to depend on methods it never calls. Size the interface to the consumer.
Suppose a settings screen needs to read and update a name, while the profile screen only reads it. Two narrow contracts serve both:
abstract class UserReader {
Future<String> fetchName(int id);
}
abstract class UserWriter {
Future<void> updateName(int id, String name);
}
class SqliteUserRepository implements UserReader, UserWriter {
final Map<int, String> _rows = {}; // stands in for a real database
@override
Future<String> fetchName(int id) async => _rows[id] ?? 'Unknown';
@override
Future<void> updateName(int id, String name) async {
_rows[id] = name;
}
}One class can implement several contracts. ProfileViewModel takes a UserReader and cannot accidentally write. A fake for the profile tests only needs fetchName. This is the interface segregation principle, and it is worth applying only when consumers really do need different subsets. Do not split by reflex.
Choosing a name
Name the abstraction after the role, and the implementations after the mechanism. UserRepository with HttpUserRepository, CachedUserRepository, and FakeUserRepository reads well. Avoid the IUserRepository prefix and the UserRepositoryImpl suffix. Dart style does not use the I prefix, and Impl tells a reader nothing about how the class differs.
Common errors
- Declaring the concrete type anyway. Writing
final ApiUserRepository _repository;while passing the object in through the constructor keeps the coupling. Check the field and parameter types, not just the constructor. - Creating an abstraction with one implementation and no purpose. An interface with a single implementation and no test double is overhead. Add one when there is a second implementation, a test that needs a fake, or a boundary you expect to change, such as network or storage.
- Mirroring the implementation's API. If the contract has
get(String url)andpost(String url, Map body), it is HTTP in disguise. Describe the capability (fetchName,updateName). - Leaking exceptions and return types. See the section above. Test this by asking whether the view model would still compile if you deleted the package import from the implementation.
- Fakes that extend the real class. The real constructor runs, and forgotten overrides call real code. Use
implements. - Changing a contract silently. Adding a method to an abstract class breaks every implementer at compile time. That is helpful for your own code but disruptive across package boundaries. If the abstraction ships in a published package, think before adding members.
Putting it together
The view model only changes in its field type, which is the point:
import 'package:flutter/foundation.dart';
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
String? error;
Future<void> load(int id) async {
try {
name = await _repository.fetchName(id);
error = null;
} on UserNotFoundException {
name = null;
error = 'No such user';
}
notifyListeners();
}
}It needs no import of http, and it works with HttpUserRepository, a cached version, or FakeUserRepository. The next chapter shows where the choice of implementation is made, in the composition root.
Exercise
A teammate writes class FakeUserRepository extends ApiUserRepository for tests and overrides only fetchName. Later someone adds Future<void> refresh() to ApiUserRepository, and a test starts making real network calls. Which two changes prevent this, and why does each help?
Show answer
First, make the view model depend on the abstract UserRepository instead of ApiUserRepository, so tests are not tied to the real class. Second, make the fake use implements UserRepository instead of extends ApiUserRepository. An implements fake inherits no real code and runs no real constructor. If a method is added to the contract, the fake fails to compile until it overrides that method, so no real network call can happen by accident.
Exercise
UserRepository.fetchName is declared to throw UserNotFoundException. The view model, though, catches http.ClientException. What goes wrong when you switch to a SQLite-backed repository, and how do you fix it?
Show answer
The SQLite implementation never throws http.ClientException, so the view model's error handling never runs and failures escape as unhandled errors. The view model also still imports package:http, so the abstraction leaks the old implementation. Fix it by having each implementation catch its own library's errors and throw the contract's exception, then have the view model catch only UserNotFoundException.