Quote needed: Preprocessor usage is bad OO practice

后端 未结 14 1472
失恋的感觉
失恋的感觉 2020-12-09 04:29

I believe, that the usage of preprocessor directives like #if UsingNetwork is bad OO practice - other coworkers do not. I think, when using an IoC container (e.

14条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 04:46

    I have no guru statement regarding to the usage of preprocessor directives in my mind and can not add a reference to a famous one. But I want to give you a link to a simple sample found at Microsoft's MSDN.

    #define A
    #undef B
    class C
    {
    #if A
       void F() {}
    #else
       void G() {}
    #endif
    #if B
       void H() {}
    #else
       void I() {}
    #endif
    }
    

    This will result in the simple

    class C
    {
       void F() {}
       void I() {}
    }
    

    and I think it is not very easy to read because you have to look at the top to see what exactly is defined at this point. This is getting more complex if you have defined it elsewhere.

    For me it looks much simpler to create different implementations and inject them into a caller instead of switching defines to create "new" class definitions. (... and because of this I understand why you compare the usage of preprocessor defintions with the usage of IoC instead). Beside the horrible readability of code using preprocessor instructions, I rarely used preprocessor definitions because they increase the complexity of testing your code because they result in multiple paths (but this is a problem of having multiple implementations injected by external IoC-Container, too).

    Microsoft itself has used a lot of preprocessor definitions within the win32 api and you might know/remember the ugly switching between char and w_char method calls.

    Maybe you should not say "Don't use it". Tell them "How to use it" and "When to use it" instead. I think everyone will agree with you if you're coming up with good (better understandable) alternatives and can describe the risks of using preprocessor defines/makros.

    No need for a guru... just be a guru. ;-)

提交回复
热议问题