Quote needed: Preprocessor usage is bad OO practice

后端 未结 14 1474
失恋的感觉
失恋的感觉 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 05:02

    Preprocessor directives in C# have very clearly defined and practical uses cases. The ones you're specifically talking about, called conditional directives, are used to control which parts of the code are compiled and which aren't.

    There is a very important difference between not compiling parts of code and controlling how your object graph is wired via IoC. Let's look at a real-world example: XNA. When you're developing XNA games that you plan to deploy on both Windows and XBox 360, your solution will typically have at least two platforms that you can switch between, in your IDE. There will be several differences between them, but one of those differences will be that the XBox 360 platform will define a conditional symbol XBOX360 which you can use in your source code with a following idiom:

    #if (XBOX360)
    // some XBOX360-specific code here
    #else
    // some Windows-specific code here
    #endif
    

    You could, of course, factor out these differences using a Strategy design pattern and control via IoC which one gets instantiated, but the conditional compilation offers at least three major advantages:

    1. You don't ship code you don't need.
    2. You can see the differences between platform-specific code for both platforms in the rightful context of that code.
    3. There's no indirection overhead. The appropriate code is compiled, the other isn't and that's it.

提交回复
热议问题