design-patternsvirtualprivatetemplate-method-patternnon-virtual-interface

private overrides of private methods pattern? (ANSWER: NVI)


What's the accepted jargon (if any) for describing methods meant to be invoked only virtually and from other methods in the base? I've occasionally seen this referred to as a callback, but that seems to stray pretty far from the original definition of that term. I'm not even sure that this merits being called a pattern, but I'm trying to become more precise in commenting my code. Thanks for the help!

// Abstract class.
class A {
public:
  void run() { while (call()) { /* ... */ } }
private:
  virtual bool call() = 0;
};

// Completion/specialization of A.
class B : public A {
private:
  // Standard term to indicate this pattern?
  bool call();
};

Summary: This appears to be called the Non-Virtual Interface pattern, a special case of the Template Method Pattern. Thanks to Nick and Steven for the help!


Solution

  • This is sometimes called the "non-virtual interface" (or NVI) pattern. It is often used when the implementation for the virtual function needs to vary between derived classes, but the base class needs control over when the function is called.

    For example, the base class could make another function call before or after the virtual call instead of making the virtual function public and relying on overrides to call the base implementation themselves (and at the right time!)