Non-Virtual Interface Pattern

« Back to Glossary Index

Description


The Non-Virtual Interface (NVI) pattern controls how methods in a base class are overridden. Base classes use public, non-virtual functions that can be called by clients. Overridable methods are defined as protected, virtual members.

Problem

When creating an abstract base class, there is a tendency to make public methods virtual or abstract, allowing them to be overridden by subclasses.

When a base class method is overridden by a subclass, the subclass’s implementation may optionally call the base class method. However, this is not mandatory, and it is not easily enforced, so it is possible that key functionality implemented in the base class is not used in a subclass. This makes these classes harder to use correctly. Wouldn’t it be better if there was a way to enforce the use of key functionality in the base class?

Solution

The NVI pattern separates the core functionality of the base class from the public interface of the base class.

  • Public methods of the base class are neither virtual nor abstract, and cannot be overridden. Functionality that must be maintained in subclasses is contained in public members of the base class.
  • Public methods call protected, virtual members in the base class. These functions contain core functionality that may be overridden by subclasses, or they may be pure abstract functions that must be implemented by the derived class.

This pattern results in two distinct interfaces:

  1. The public interface used by clients
  2. The private interface, which is used, extended, and/or implemented by subclasses.
Note

While this pattern is usually used with class interfaces, the same ideas apply to library and framework interfaces.

Consequences

  • This pattern mitigates the Fragile Base Class interface problem.
  • This pattern requires minimal overhead to implement, but represents a reorganization of the base class’s functionality.

Known Uses

References

Non-virtual_interface_pattern (Wikipedia)

The non-virtual interface pattern (NVI) controls how methods in a base class are overridden. Such methods may be called by clients and overridable methods with core functionality. It is a pattern that is strongly related to the template method pattern. The NVI pattern recognizes the benefits of a non-abstract method invoking the subordinate abstract methods. This level of indirection allows for pre and post operations relative to the abstract operations both immediately and with future unforeseen changes. The NVI pattern can be deployed with very little software production and runtime cost. Many commercial software frameworks employ the NVI pattern.

Synonyms:
NVI Pattern, Non-Virtual Interface
Categories: Field Atlas


« Back to Glossary Index

Share Your Thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.