Junior
What is abstraction in programming?
sobes.tech AI
Answer from AI
Abstraction is a mechanism that allows hiding implementation details and showing only the necessary information. In the context of OOP, abstraction is achieved through abstract classes and interfaces. They define a contract (a set of methods) that concrete classes must implement without revealing how these methods work.
Advantages of abstraction:
- Simplification of complex systems.
- Increased flexibility and extensibility.
- Reduced dependency between modules.
- Improved maintainability of code.
Example of an abstract class in Flutter:
// Defines the basic behavior of a data repository
abstract class DataRepository {
// Abstract method for fetching data, without implementation details
Future<List<String>> fetchData();
// Can contain an implemented method if it is common for all subclasses
void dispose() {
// Resource release logic if needed
}
}
// Concrete implementation of a repository from an external source
class RemoteDataRepository implements DataRepository {
@override
Future<List<String>> fetchData() async {
// Details of fetching data over the network
await Future.delayed(Duration(seconds: 2)); // Simulating delay
return ['Data from network 1', 'Data from network 2'];
}
}
// Concrete implementation of a repository from cache
class CacheDataRepository implements DataRepository {
@override
Future<List<String>> fetchData() async {
// Details of fetching data from local cache
return ['Data from cache 1', 'Data from cache 2'];
}
}
Here, DataRepository abstracts the process of data fetching, allowing work with different data sources (remote or cache) through a unified interface. Client code interacts only with DataRepository, without knowing the specific implementation.