Saturday, February 25, 2012

Encapsulation vs Abstraction

The difference between encapsulation and abstraction is, well, abstract. Encapsulation hides implementation details, and for abstraction, the interface is of more importance.

It is best to explain with example.

Say in a web application, we want to detect user's geolocation based on the IP address, and say we are using a 3rd party geolocation database called RemoteGeoLocationDB to do the same.

Good Encapsulation, Bad Abstraction

Array MyGeoLocationService.getGeoLocationData(HttpHeaders)
The good: single API, hides RemoteGeoLocationDB
The bad: accepts all HTTP headers, returns an Array of geolocation data.

Good Encapsulation, Good Abstraction

IPAddress = HttpHeaders.getIPAddress()
GeoLocationObject MyGeoLocationService.getGeoLocationObject(IPAddress)
Better abstraction than the above: 1. geolocation does not require all HTTP headers, and 2. returns a well defined object rather than array of possibly name-value pairs.

Encapsulation and abstraction go hand in hand: you abstract your implementation into well defined interfaces, and then encapsulate your logic and data inside those interfaces. However, it is possible to implement something which is abstracted but not encapsulated (reveals too much details), and it is possible to implement something which is encapsulated but not abstracted (bad interfaces).

No comments:

Post a Comment