Search code examples
c++inheritancedesign-patternsthrift-protocol

Apache thrift "TProtocol class" design principle - C++ ,why do we need "writeBool()"


At present ,i have been reading the source code of "Apache Thrift".More specifically, the code which is implemented by C++, is put in this path: "thrift-0.9.1.tar\thrift-0.9.1\lib\cpp".

I have been wondering why "TProtocol class" is designed like this:

As we know "TProtocol Class" is an abstract class. And there is a detailed analysis here: "developermemo". And it says "Also defines a corresponding abstract factory class for the production of specific protocol object, which is the most commonly used design patterns abstract factory design pattern. "

However, I was wondering why they define a function of the corresponding pure virtual function is called. For example:

  virtual uint32_t writeSetEnd_virt() = 0;
  virtual uint32_t writeBool_virt(const bool value) = 0;  //Pure virtual function

  uint32_t writeBool(const bool value) {                  //
  T_VIRTUAL_CALL(); 
  return writeBool_virt(value);                           //call the "interface"
  }

Why do we need "writeBool()". It seems that it is useless. Why do not we just define the "pure virtual functions" and "the derived classes" rewrite these interfaces.


Solution

  • This is a pattern called 'template method'. You often have this combination of a public, nonvirtual function and a private, virtual function. Apart from forwarding, the public one does things like checking preconditions and postconditions, logging and simple conversions. The private, virtual one does the actual work. The rationale for making it private is to make clear that you don't have the choice to call the base version, which you can do otherwise with an explicit derived.base::foo() call. If you need to extend the base version, you can also make it protected instead, but that isn't the case here.