Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why table and tablebuilder in leveldb use struct rep?

Recently I read the source code of leveldb, but I am confuse about the rep struct in the table and table_builder source.

since we can directly store the member variable directly in the class Table and class TableBuilder.

But why the author make a struct Rep, and store the member variable in the struct Rep.

I can come up whit one reason, because the table and table_builder will expose to the user, so we want to hidden the implementation. Is it right? or there is some other idea that I miss, or is it some design pattern?

Thank you

like image 710
baotiao Avatar asked Oct 30 '15 02:10

baotiao


1 Answers

Here is a code snippet extracted from table.h, and a code-snippet from table_builder.h would have shown a similar design

class Table 
{
    ...
    struct Rep;
    Rep* rep_;
    ...
};

Thus, the explanation you came up with is the right one:

  • The declarations of the classes table.h and table_builder.h are exposed to the leveldb clients;
  • However, the designer did not want to expose the internal representation of the data, as they are implementation details and are unnecessary in an interface;
  • Thus these details have been moved out into a separate structure, the structure Rep which is declared in the public interfaces (the header files) but is defined and used only in the implementation files (the source files);
  • This is a fairly common idiom, often called the pImpl idiom (since the pointer to the implementation often is called pImpl) or a compilation firewall.

Besides design encapsulation, there is another reason for this idiom, which is usability. Indeed, if the internal details of Table were exposed in Table.h, any leveldb user's source file that includes Table.h would have to be recompiled each time these details change.

By hiding away these implementation details, leveldb users' source files are unaffected by changes in the leveldb data internal representation. As long as the leveldb public interface (the public header files) doesn't change, users can upgrade from one version of leveldb to another one without ever recompiling their source code: they just need to link with the new version of the leveldb library.

Thus, this idiom is extremely important for library developers, and may be used as well to minimize coupling between distinct modules of a program.

like image 50
Daniel Strul Avatar answered Sep 29 '22 11:09

Daniel Strul