1

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?

shadesofdarkred
  • 313
  • 3
  • 15
  • If I'm designing something and it looks weird, I usually rethink and probably not use that design. It will just speak to the difficulty I will have when future me goes back to this code to figure out what's happening. I'm not sure if this will help, but, I remember asking myself why I should use mixins when I was first trying to mess around with them. I mostly ended up just creating an interface exposing what methods *needed* to be implemented and adapting my code for that interface (I tend to gravitate towards the hexagonal architecture pattern). – idjaw May 27 '21 at 17:21
  • Perhaps [this](https://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful) answer can help a bit to provide some breakdown/comparison? This is not to say they should not be used. I hardly found cases for them in my own personal experience. Maybe it will help clarify its usage for you and you can still find good use for it! Hope this helps. – idjaw May 27 '21 at 17:21

0 Answers0