OOPMidMCQ
What's the difference between abstraction and encapsulation?
Test your knowledge:
Explanation & Code
Answer: They're often confused because both involve "hiding" something, but they hide different things for different reasons:
- Encapsulation hides internal state to protect it from invalid mutation (an implementation detail / data-integrity concern).
- Abstraction hides implementation complexity behind a simpler interface, so callers depend on what something does, not how (a design / interface concern).
protocol ImageLoader {
func load(url: URL) async throws -> UIImage
}
// Caller only knows the abstraction...
func showAvatar(loader: ImageLoader, url: URL) async {
let image = try? await loader.load(url: url)
}
// ...not that this implementation encapsulates a cache and a URLSession
final class CachingImageLoader: ImageLoader {
private var cache: [URL: UIImage] = [:] // encapsulated state
private let session = URLSession.shared
func load(url: URL) async throws -> UIImage {
if let cached = cache[url] { return cached }
let (data, _) = try await session.data(from: url)
let image = UIImage(data: data)!
cache[url] = image
return image
}
}
Rate your understanding: