I'm exploring clean architecture and have noticed in many articles and videos that they pass packages/plugins to the data source. For instance, using SharedPreferences for the local data source and http for the remote data source. So, I have a few questions:
Could you provide suggestions on how to tackle this problem?
Example - datasource class using http.client
class NumberTriviaRemoteDataSourceImpl implements NumberTriviaRemoteDataSource {
final http.Client client;
NumberTriviaRemoteDataSourceImpl({@required this.client});
Future<NumberTriviaModel> _getTriviaFromUrl(String url) async {
final response = await client.get(
url,
headers: {
'Content-Type': 'application/json',
},
);
if (response.statusCode == 200) {
return NumberTriviaModel.fromJson(json.decode(response.body));
} else {
throw ServerException();
}
}
}
Recommended way to deal with this is using Abstraction. High-level modules should not depend on low-level modules. Both should depend on abstractions. So if you need to change packages/plugins later, you only need to create new implementations of these abstract classes without touching the existing logic in your data source classes.
Using the above concept, if you're using HTTP with specific headers across multiple data sources, creating a wrapper class can centralize the logic for headers and simplify your data source classes.
Study Dependency Injection, you can easily swap them out without modifying the existing logic.
Here's an example