G2Labs Grzegorz Grzęda
Implementing the Null Object Pattern in C++ and C
April 30, 2023
Implementing the Null Object Pattern in C++ and C
In programming, especially when developing complex applications, maintaining a consistent structure is crucial. However, you might encounter scenarios where you need to implement a placeholder functionality that essentially does nothing. This is where the Null Object pattern becomes handy.
The Logger Example: A C++ Approach
Consider a simple calculator application in C++. The application performs basic tasks and logs each step to the standard output.
Project Structure
ILog Interface
ILog.hpp
is an interface with a single method for logging:
ConsoleLog Implementation
ConsoleLog.hpp
prints messages to stdout
:
CalcModel Class
CalcModel.hpp
is a simple calculator with logging:
Main Function
The main.cpp
file manages inputs and logs operations:
Introducing Null Object Pattern
To disable logging as per a client’s request, we introduce NullLog
:
In main.cpp
, we conditionally use NullLog
:
Extending the Example: A C Approach
In C, implementing the Null Object pattern can be more challenging due to the lack of polymorphism. However, we can use function pointers to achieve a similar effect.
Logger in C
Define a logger function pointer and two logging functions:
Using Logger in a C Program
In your C program, you can now choose which logger to use:
Conclusion
The Null Object pattern in C++ and C offers a way to seamlessly switch between active functionality and a ‘do-nothing’ behavior. It’s particularly useful in scenarios where you need to maintain a consistent structure but require the flexibility to disable certain functionalities without altering the overall architecture. This pattern not only keeps your code clean but also prevents the system from branching into multiple versions for different needs.