I’m working on a python class that is being shared between two products. 90% of the functionality applies to both products. For the 10% that’s different the code is littered with this kind of thing:
#Start of file
project = 'B'
#Some line of code
if project == 'A':
import moduleA
elif project == 'B':
import moduleB
#Many lines of code
if project == 'A':
print moduleA.doA(2)
elif project == 'B':
print moduleB.doB(2)
This doesn’t seem very elegant or very readable, has anyone encountered this sort of thing before? Are there better ways of doing it?
No, as this is very poor design. If your module’s behavior is influenced by the project in which it is used, then it should accept an object, function, or other callback for the project-specific behavior. My suggestion is to factor out the pieces that are shared and make them into a single module, and for anything that is project-specific, add a dependency on an object that needs to be passed in, and require that the object conform to some interface. Then, wrap your project-specific behaviors in an object that conforms to the required interface and pass it to the common, shared module.