Saturday, May 3, 2014

Widgets

Precise Difference between Encapsulation and Abstraction

A priori, they've got nothing in common.
point x = { 1, 4 };
point y = { 23, 42 };

int d = distance(x, y);
Here, distance encapsulates the calculation of the (euclidean) distance between two points in a plane: it hides implementation details. This is encapsulation, pure and simple.
Abstraction is the process of generalization: taking a concrete implementation and making it applicable to different, albeit somewhat related, types of data. The classical example of abstraction is C's qsortfunction which sorts data.
The thing about qsort is that it doesn't care about the data it sorts – in fact, it doesn't know what data it sorts. Rather, its input type is a typeless pointer (void*) which is just C's way of saying “I don't care about the type of data” (this is also called type erasure). The important point is that the implementation of qsort always stays the same, regardless of data type. The only thing that has to change is the compare function, which differs from data type to data type. qsort therefore expects the user to provide said compare function as a function argument.
Encapsulation is hiding the implementation details which may or may not be for generic or specialized behavior(s).
Abstraction is providing a generalization (say, over a set of behaviors).

No comments:

Post a Comment