Pre-Compiler Directives That Make Sense

The [last blog article](/posts/sonar_code_duplicates/) was dealing with the same linked file in different projects. A reason could be, that some code needs to be compiled with different frameworks. In my case, I had to compile business logic with Microsoft CSOM for SharePoint 2016 and Microsoft CSOM for SharePoint Online. The API is more or less the same, but there is no abstraction layer so I have the write or compile the same code twice. Adding the file as a link has some advantages

  • No need to copy and paste the code
  • A bug fix is done in both files at the same time
  • Static code analysis (SonarQube) does not count the code as duplicates lines

At least for the bug-fixing part, it has a lot of advantages. But what happens if the code needs to access two different classes which are not shared across the projects or the frameworks have different usages or parameters?

In [another article](/posts/mode-detector-vs-precompiler-directive/), I used a `ModeDetector` class to handle different code for different cases e.g. debug and release build. But this does not work if the usage differs for different frameworks. In this sample, I have different classes `Console2016` and `ConsoleOnline` but these could be classes in a 3rd party framework I am unable to change. The code does not compile because the same code cannot be used to invoke the `Console`.

![VS Sample solution](/assets/posts/2021-09-29-same_file_different_code_error.png)

So in the end we need to use precompiler directives again to execute different code. The project settings allow a space-separated set of customer variables that can be easily checked in code. The two different projects define different compiler variables and the code compiles one or the other if-branch.

This is not a problem according to the assumptions made for the mode detector. The mode detector tries to avoid code that is not always compiled. In debug mode, the release code is removed and the compiler does not show warnings on refactoring. In our case, both code paths will be compiled, but in different projects. So a compiler error will occur on a client build.

In this case, a precompiler directive makes sense and it is used to reduce code duplications and compile different code depending on the environment or framework.


Posted

in

Kommentare

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert