cover-img

Code Smell 56 - Preprocessors

We want our code to behave different on different environments, operating systems, so taking decisions at compile time is the best decision, isn't it?.

17 March, 2023

0

0

0

We want our code to behave different on different environments, operating systems, so taking decisions at compile time is the best decision, isn't it?.

Problems

  • Readability
  • Premature Optimization
  • Unnecessary complexity
  • Debugging

Solutions

  1. Remove all compiler directives.
  2. If you want different behavior, model it with objects
  3. If you think there's a performance penalty, make a serious benchmark instead of doing premature optimization.

Sample Code

Wrong

#if VERBOSE >= 2
printf("trace message");
#endif

Right

if (runtimeEnvironment->traceDebug()) {
printf("trace message");
}

## even better with polymorphism and we avoid annoying ifs

runtimeEnvironment->traceDebug("trace message");

Detection

This is a syntactic directive promoted by several languages, therefore it is easy to detect and replace with real behavior.

Tags

  • Compilers
  • Metaprogramming

Conclusion

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.

Relations

Code Smell 20 - Premature Optimization

More Info

Laziness I - Metaprogramming

C++Faq

C Preprocessor

#ifdef Considered Harmful

Credits

Photo by CDC on Unsplash


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.

How to Find the Stinky Parts of your Code


0

0

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.