Junior — Middle
Could you explain the interface segregation principle in object-oriented programming?
sobes.tech AI
Answer from AI
The Interface Segregation Principle (ISP) states that it is better to create several specialized interfaces rather than one general-purpose interface. Clients should not depend on methods they do not use.
In practice, this means that if you have an interface with many methods and different classes only use some of them, it is better to split the interface into smaller, more specific ones. This increases flexibility and makes the code easier to maintain.
For example, in iOS, you can separate the interface for network operations and database operations:
protocol NetworkService {
func fetchData()
}
protocol DatabaseService {
func saveData()
}
class DataManager: NetworkService, DatabaseService {
func fetchData() {
// implementation for data fetching
}
func saveData() {
// implementation for data saving
}
}
Thus, if a class only uses network functions, it can depend solely on NetworkService, without knowing about data saving methods.