I have a question about which pros and cons of each paradigm. Let me explain:
Imagine I need to implement a class that will read and write. However, I want to keep the exact way of reading and writing flexible. One way to do that is to require a reader and a writer on initialization:
class System:
def __init__(self, reader, writer):
self.reader = reader
self.writer = writer
class Reader:
def read(self):
pass
The reader has to implement read
method and the writer has to implement write
method. This way, I can call self.reader.read()
anywhere in the class methods and know that code will work as expected; similarly for writer.
If someone wants to implement a new read or write functionality, they would have to write a class that honors the above interface.
Alternatively, I can define ReaderMixin
and WriterMixin
and require these mixin class implement read
and write
methods. Then my main class would look like
class System(ReaderMixin, WriterMixin):
pass
class ReaderMixin:
def read(self):
pass
Because I inherit new methods from both mixins, I can now call self.read()
anywhere in the code and know that code will work as expected.
If someone wants to implement a new read or write functionality, they would have to write a new mixin class which honors the above interface.
Both of these methods seem to work but I feel some awkwardness with both too. Are there conditions where one is preferred over another? What are the best practices for situations like this?