Drawbacks of the Non-Virtual Interface
There aren’t many drawbacks regarding the use of the NVI. That is why the guideline to always make virtual functions private, and use the NVI to call them, is widely accepted. However, there are some considerations that you must be aware of when deciding whether the Template Method is the right design pattern to follow. The use of the template pattern may lead to fragile hierarchies. Also, there is some overlap between design problems that can be solved using the template pattern and the ones better served by the strategy pattern, or, in C++, policies. We will review both considerations in this section.
Composability
Consider the earlier design for LoggingFileWriter
. Now, suppose that we want to also have CountingFileWriter
that counts how many characters were written into the file:
class CountingFileWriter : public FileWriter { size_t count_ = 0; void Preamble(const char* data) { ...