It’s well known recomendations that:
- 1) class or function should have one responsibility
- 2) variable should not be reused in different contexts
We can generalize this recomendations to general rule:
Symbol should have one meaning.
Then, for example in crossplatform development is often used similar code:
#ifdef _WIN32
class CFoo {
/* ... */
};
#elif _LINUX
class CFoo {
/* ... */
};
#endif
With this code, when you later refer to CFoo
, it can have three meanings:
CFoo
as Win32 platform specific classCFoo
as Linux platform specific classCFoo
as crossplatform class
So, when you use CFoo
symbol somewhere, its not exactly clear which CFoo
it is.
Violates similar code “essence” of recomendations 1) or 2) ?
0
A question about the word “meaning” should not be discussed in meaningless terms like CFoo
.
Lets make a better example:
#ifdef _WIN32
class MyUsbDriver {
/* ... a public API to access a special USB devcice.. */
/* ... internal implementation: Windows sepecific.. */
};
#elif _LINUX
class MyUsbDriver {
/* ... exactly the same API as in the WIN32 version.. */
/* ... internal implementation: Linux sepecific.. */
};
#endif
That way you create an abstraction for an Usb-Driver, so for the code actually using that class both variants have the same meaning – from that point of view. Ideally, for the calling code, there should be no visible difference between the two classes.
Note that in C++, you have much better means for creating such abstractions than using the preprocessor. For such a situation it would probably be preferable to make MyUsbDriver
an abstract interface class, with derived classes MyUsbDriverWin32
and MyUsbDriverLinux
. However, you will probably have to encapsulate those two derived classes in #ifdef
blocks, since otherwise you might not be able to compile each class in the environment it was not designed for.
What you should avoid is something like
#ifdef _WIN32
class MyUsbDriver {
/* ... a public API to access a special USB devcice.. */
};
#elif _LINUX
class MyUsbDriver {
/* ... a completely different API as in the WIN32 version.. */
/* ... or (worse): a similar looking API, with a different behaviour */
};
#endif
that would be somehow similar to “reusing the same variable in different contexts twice”.