We want our code to behave differently on different environments, and operating systems, so taking decisions at compile time is the best decision, isn't it?.
TL;DR: Preprocessors make some unnecessary magic
-
Readability
-
Premature Optimization
-
Unnecessary complexity
-
Debugging
-
Remove all compiler directives.
-
If you want different behavior, model it with objects
-
If you think there's a performance penalty, make a serious benchmark instead of doing premature optimization.
#if VERBOSE >= 2
printf("trace message");
#endif
if (runtimeEnvironment->traceDebug()) {
printf("trace message");
}
// even better with polymorphism and you avoid annoying ifs
runtimeEnvironment->traceDebug("trace message");
This is a syntactic directive promoted by several languages, therefore it is easy to detect and replace with real behavior.
-
Compilers
-
Metaprogramming
Adding an extra layer of complexity makes debugging very difficult. This technique was used when memory and CPU were scarce. Nowadays, we need clean code and we must leave premature optimization buried in the past.
Bjarne Stroustrup, in his book The Design and Evolution of C++, regrets on the pre-processor directives he created years before.
Code Smell 20 - Premature Optimization
C++ is designed to allow you to express ideas, but if you don't have ideas or don't have any clue about how to express them, C++ doesn't offer much help.
Bjarne Stroustrup
Software Engineering Great Quotes
This article is part of the CodeSmell Series.