In python, let's assume I have a MainClass
that on initialization expects an implementation of AbstractClass
and then uses it internally, i.e.:
def __init__(self, anInstanceOf:AbstractClass): [...]
During testing I inject FakeTestClass
to verify MainClass calls on the facilities implied by AbstractClass as expected. FakeTestClass inherits from AbstractClass and implements it:
class FakeTestClass(AbstractClass): [...]
In the production code however I must inject an instance of ThirdPartyLibraryClass
that provides the functionality MainClass actually needs but does not inherit from AbstractClass, it only provides identical method signatures.
In python this works because typing is not strictly enforced.
I do have a bit of a nagging feeling though. I'd like to always inject objects that inherit from AbstractClass as requested by the type hint in MainClass.__init__
What are my options? I can think of a few:
- ignore the issue: if it behaves like a duck it is a duck, the type hint is just that, a hint for the reader
- write a wrapper: the wrapper inherits from AbstractClass but forwards calls to an instance of ThirdPartyLibraryClass it holds: simple conceptually, but it requires forwarding every call (statically or via metaprogramming) or at least the subset implied in AbstractClass
- write a thin wrapper: (as per post title) simply inherits from both ThirdPartyLibraryClass and AbstractClass, but is empty and provides only the functionality inherited from ThirdPartyLibraryClass - feels very much like duck typing and might have unexpected behaviour due to the multiple inheritance?
- Others?
Aucun commentaire:
Enregistrer un commentaire