[Exceptional C++ Style] Item 17 - Encapsulation

solosnake . solosnake at hotmail.com
Mon Dec 20 04:37:21 EST 2004


Item 17: Encapsulation
======================

Summary
-------

This article discusses what encapsulation means within C++ programming, and
how it should be properly implemented.

First the English language meaning of encapsulate is discussed, and
analogies between encapsulation as protection in nature and in C++ class
design are drawn. Encapsulation in programming is said to protect the
internal implementation of a class by hiding these internals and providing
an interface of functions that act upon these internals. External code
should not depend on the class internals. The class interface should
guarantee that all access and manipulation of internal structures preserves
class invariants.

Then the importance of encapsulation to Object-Oriented programming is
discussed. The author says that encapsulation is the prime concept in
object-oriented programming, and that the other aspects of OO programming
are important principally because they support special cases of
encapsulation. He gives supporting examples of data hiding and separation of
interface from implementation (using run-time polymorphism or compile-time
polymorphism via templates) as methods of implementing encapsulation in OO
code. Data hiding and polymorphism are always forms of encapsulation.
Benefits of encapsulation are high cohesion, low coupling and management of
dependencies.

Next the author considers public, protected and private data members, and
asks for a coding guideline as to when they should be used. He says the
guideline should be that data members always be private, except in the
special case when all class members (functions and data) are public, and the
object is not really a class but just a C-style collection of data. Except
in this special case, both public and protected data is "evil", and should
never be used. He proves this using a reductio-ad-absurdum approach. The
std::pair is used as an example of the special case where both functions and
data are public, but the author says that it would have been equally useful
had it been encapsulated.

The author says that the most important thing to get right is the class
interface - everything else can be fixed. Poor interfaces may be impossible
to fix once in use.

==========

Daire Stockdale

Merry Christmas!





More information about the Effective-cpp mailing list