0

I have a class Library which defines some methods on - kind of - abstract data. This class is then inherited into a class A or B that actually defines the data. The intention is to reuse Library with different underlying data storage models.

In Python:

class Library:
    def meth1(self, ...):
      return ...
    def meth2(self, ...):
      return ...
    def compute_property1(...):
      return ...
    def compute_property2(...):
      return ...

class B(Library):
    property1 = property(lambda s: s.compute_property1()) #plain property
    property1 = property(lambda s: s.compute_property2()) #plain property

class A(Library):
    property1 = my_property_with_fancy_caching_and_compression_and_stuff(....)
    property1 = my_property_with_fancy_caching_and_compression_and_stuff(....)

Is this pattern a well-known design approach? Does it have a name? Is there a recommended name for Library?

Michael
  • 7,407
  • 8
  • 41
  • 84

1 Answers1

1

Your example is leveraging Python's Multiple inheritance mechanism, whereby you add methods from a methods-only, data-free, abstract class A, to one (or several) data-oriented, dumb concrete class B.

As it separates data-storing (representation) from functionality (methods), it is very close to a mixin as Bruno commented, but with the distinction that such pattern usually brings both data storage and functionality. This difference in your pattern makes it not completely OOP (where an object is supposed to bring both) but is reminiscent of the Aspect-Oriented paradigm.

If I were to describe this mechanism in OOP, I'd call class A an interface with default methods. That would carry the ability to import anywhere some methods implementations, but no fields. And I would call class B Data Access Object

Note: If you intend to do so for several interfaces (e.g., if you were to split your meth1() and compute_priority_1()from meth2() and comute_priority_2() from each other, and place them in two separate interfaces), then that would follow Interface Segregation Principle.

Community
  • 1
  • 1
MrBrushy
  • 680
  • 3
  • 17
  • Thanks for that thorough analysis :-) Is there a recommendable book about those topics? (So far, I only worked through the classical "Design Patterns", but I find it a bit ... well .... not-tought-to-an-end ...?) ) – Michael Oct 11 '16 at 11:36
  • 1
    StackOverflow is probably goo enough. Then you'll need to confront reality to find something 'thought-to-an-end'. Very rarely are Design-Patterns explained in a use-case complete enough. I have read a lot, but ulitmately it is down to: 1) Lift your pen 2) Define what your goal 3) Think hard on the OOP tools you have (Interfaces, fields, generics...) 4) Write what you want your usage code to look like ideally (how to USE the DP) 5) Make it happen. – MrBrushy Oct 11 '16 at 12:46