Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ advice from Code Complete on encapsulation?

In the section on "Good Encapsulation" in Code Complete, it is recommended to hide private implementation details. An example is given in C++. The idea is basically to completely separate the interface from the implementation, even in the class level.

class Employee {
public:
    ...
    Employee( ... );
    ...

    FullName GetName() const;
    String GetAddress() const;

private:
    EmployeeImplementation *m_implementation;
};

Is this really a good use of time? Not only does this seem inefficient (what kind of performance penalties would this give?), but the whole motto of Code Complete ("managing complexity") seems to have been reversed- does this not add complexity?

like image 458
voithos Avatar asked Jun 12 '11 04:06

voithos


1 Answers

Another advantage of the PIMPL idiom may be in maintaining the ABI. See The Pimpl Idiom in practice.

The size of the class remains constant. This means that you may change the internal implementation, while keeping the interface intact.

If the implementation is distributed in compiled form (lib, dll, so, etc.), then, under some conditions, you may be able to just replace the library without having to recompile the code that uses the class. Thus, you decouple the code as a completely stand-alone module, so long as the public interface doesn't change.

As others have stated, it also reduces compilation time, which can be reason enough in some cases.

like image 180
Gilad Naor Avatar answered Sep 19 '22 23:09

Gilad Naor