Junior — Middle
Is it permissible to create a wrapper class for another class in object-oriented programming?
sobes.tech AI
Answer from AI
Creating a wrapper class around another class in object-oriented programming is permissible and often used. Such a class serves to encapsulate, extend, or modify the behavior of the original class without changing its code.
For example, a wrapper class can add logging, caching, or access control to the methods of the inner class. This aligns with the principle of composition and the "Decorator" pattern.
Example in Swift (iOS):
class Service {
func fetchData() -> String {
return "Data"
}
}
class ServiceWrapper {
private let service: Service
init(service: Service) {
self.service = service
}
func fetchData() -> String {
print("Logging fetchData call")
return service.fetchData()
}
}
let service = Service()
let wrappedService = ServiceWrapper(service: service)
print(wrappedService.fetchData())
Thus, a wrapper class helps extend functionality without inheritance and modifying the original class.