Sub topic 3
Depending on abstractions, not implementations
Assume you know Dart classes, abstract classes, implements, Flutter widgets, Future, and async/await. This chapter builds on constructor injection: a class receives the objects it needs instead of creating them internally.
Why concrete dependencies create coupling
A dependency is an object that another object needs to do its work. A profile view model might depend on a user repository to load a name.
A concrete dependency is a specific implementation, such as ApiUserRepository. If the view model creates that class itself, it becomes coupled to the network:
class ProfileViewModel extends ChangeNotifier {
final ApiUserRepository _repository = ApiUserRepository();
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
notifyListeners();
}
}This code has two problems:
- The view model cannot easily use a cache or an offline repository.
- A unit test must deal with the real repository instead of a controlled test object.
The view model should depend on an abstraction. An abstraction describes what an object can do without specifying how it does it. In Dart, an abstract class can define that contract.
Define a repository contract
The UserRepository abstraction says that an implementation can fetch a user name. It does not mention HTTP, databases, or local files.
import 'package:flutter/foundation.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async {
// A real implementation could call an HTTP client here.
return 'User $id';
}
}
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
notifyListeners();
}
}ProfileViewModel depends on UserRepository, not ApiUserRepository. Any class that implements the contract can be passed to its constructor.
This design follows the dependency inversion principle. High-level code, such as a view model, should not depend directly on low-level details, such as an HTTP client. Both should meet a stable contract.
Swap implementations safely
A fake repository can return predictable data without using a network:
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}
Future<void> example() async {
final viewModel = ProfileViewModel(FakeUserRepository());
await viewModel.load(1);
print(viewModel.name); // Test User
}The view model's code does not change. Only the object supplied at the application boundary changes. This boundary is where the app decides whether to use the API, a cache, or a fake.
The abstraction should contain the behavior that callers genuinely need. Avoid adding every method that a future implementation might want. A small contract is easier to understand and implement.
Common errors
- Depending on a concrete class in the field type while accepting an abstraction in the constructor defeats the purpose.
- Adding API-specific methods to the abstraction leaks implementation details.
- Returning different error behavior from each implementation can surprise callers. Document or standardize important failure cases.
- Making every class abstract adds ceremony. Use an abstraction when substitution, testing, or separate implementations provide a real benefit.
Exercise
Change the example so that ProfileViewModel can receive a repository that returns "Cached User" without modifying ProfileViewModel.
Show answer
Create a class such as CachedUserRepository that implements UserRepository, implement fetchName to return "Cached User", and pass CachedUserRepository to the ProfileViewModel constructor.