Medium
Null Object logger used in place of a null check
What does this program print?
main.cpp
struct Logger { virtual void log(const std::string& msg) = 0; virtual ~Logger() = default; };
struct FileLogger : Logger {
void log(const std::string& msg) override {
std::cout << "[file] " << msg << "\n";
writeCount_++;
}
int writeCount_ = 0;
};
int g_callCount = 0;
struct NullLogger : Logger {
void log(const std::string&) override {
// "do nothing" -- except it also touches shared telemetry
++g_callCount;
}
};
void runTask(Logger& logger) {
logger.log("starting task");
logger.log("task complete");
}
int main() {
NullLogger nullLogger; // used in place of a null check
runTask(nullLogger);
std::cout << "g_callCount = " << g_callCount << "\n";
}21 of 44 in Design Patterns