I am having a discussion with a colleague about using macro as a thin (extremely) layer of abstraction vs using a function wrapper. The example that I used is
Macro way.
#define StartOSTimer(period) (microTimerStart(period))
Function wrapper method
void StartOSTimer(period)
{
microTimerStart(period);
}
Personally, I liked the second method as it allows for future modification, the #include dependencies are also abstracted as well.
-
Your colleague probably thinks that somehow your version is slower. If it is, the time difference will probably unnoticeable and anyway, one can expect any decent compiler to inline the call completely where possible. Use the second method.ereOn– ereOn2012年03月29日 11:20:15 +00:00Commented Mar 29, 2012 at 11:20
-
There's nothing wrong with macros. Check out SGLIB. If misused, macros can usually do more damage than functions, but improper use of functions alone is enough to write crappy code. Look at the code (or even better: have someone look at it) and if it's self-explanatory you've done it right. Intelligent use of macros can in fact decrease noise and thereby increase clarity.back2dos– back2dos2012年12月04日 12:18:08 +00:00Commented Dec 4, 2012 at 12:18
2 Answers 2
Macros are hideous abominations that should be avoided in every situation you can possibly get away with. You'd have to have a fairly extreme justification to use one.
-
1Take a look at LLVM and Clang source code for an example of smart, clean and maintainable use of the preprocessor. Then try to think of how to do the same thing without it.SK-logic– SK-logic2012年03月29日 10:15:53 +00:00Commented Mar 29, 2012 at 10:15
-
1@SK-logic: Because they have such small codebases, I can find a suitable example easily.DeadMG– DeadMG2012年03月29日 10:58:58 +00:00Commented Mar 29, 2012 at 10:58
-
1@SK-logic: Do note that DeadMG said "You'd have to have a fairly extreme justification to use one." There are times where macros are needed. The OP's case is not one of those times.In silico– In silico2012年03月29日 11:15:27 +00:00Commented Mar 29, 2012 at 11:15
-
@DeadMG, have you ever heard of
grep
? Look for sequences of#define something
and then#include "whatever.inc"
.SK-logic– SK-logic2012年03月29日 12:50:10 +00:00Commented Mar 29, 2012 at 12:50
Since you use wrapper, you can also use it with a function pointer. If you use it as such, you can pass a stub function, and unit test functions that uses it. You can not do it with macro.