Junior — Middle
Can you give an example where the interface segregation principle is applied in practice?
sobes.tech AI
Answer from AI
The Interface Segregation Principle (ISP) states that clients should not depend on interfaces they do not use. This helps create more flexible and maintainable systems.
In Flutter, this principle is often applied when designing widgets and services. For example, if you have an interface for network operations, you should not force all classes to implement caching methods if they do not need them.
Example:
abstract class NetworkService {
Future<String> fetchData();
}
abstract class CacheService {
void saveData(String data);
String? loadData();
}
class ApiService implements NetworkService {
@override
Future<String> fetchData() async {
// Implementation of API request
return 'Data from server';
}
}
class CacheManager implements CacheService {
String? _cache;
@override
void saveData(String data) {
_cache = data;
}
@override
String? loadData() {
return _cache;
}
}
Here, classes are separated by interfaces, and each implements only the methods they need. This makes testing and maintaining the code easier.