简体   繁体   English

整体继承与基于模块化成员的OOP设计

[英]monolithic inheritance vs modular member based OOP design

I'm having a hard time making a design decision 我很难做出设计决定

I have a class in python, that processing form data, this data is very similar to other form data, and so I'm refactoring it into it's own object so it can be reused by the other classes. 我在python中有一个类,用于处理表单数据,此数据与其他表单数据非常相似,因此我将其重构为自己的对象,以便其他类可以重用。

The delima is weather to make this formprocessor a member of the classes or a parent of the classes. 要使此表单处理器成为类的成员或类的父级,这是一个很大的挑战。

please correct me if this terminology is wrong, here is what I'm torn between: 如果此术语错误,请更正我,这是我之间的误解:

monolithic inheritance based classes: 基于整体继承的类:

class FormProcessor(object):
    def post(self):
        # ... process form data

class PageHandler(RequestHandler,FormProcessor):
    def get(self):
        # show page

or the more modular member based classes: 或更模块化的基于成员的类:

class FormProcessor(object):
    def process(self):
        # ... process form data

class PageHandler(RequestHandler):
    def __init__(self):
        self.processor = FormProcessor()
    def get(self):
        # show page

    def post(self):
        self.processor.process(self.postdata)

I'm leaning toward the second but I'm not sure what the consequences could be down the road in terms of maintainability. 我倾向于第二种,但是我不确定在可维护性方面会带来什么后果。 The reason I'm leaning toward it is that, I like to think of the processing as an action that takes place, not as a main part of the PageHandler, so this makes sense to make it a member object, instead of a parent. 我倾向于它的原因是,我喜欢将处理视为发生的动作,而不是PageHandler的主要部分,因此将其设为成员对象而不是父对象是有意义的。

It bothers me that when classes interit functionality it ends up with a very long list of functions on an instance, I'm trying to categorize them better so the program is understandable and reflects the system that it is modeling. 令我感到困扰的是,当类插入功能时,它最终会在实例上列出很长的功能,因此我试图对它们进行更好的分类,以便程序易于理解并反映所建模的系统。

look forward to any advice on this issue 期待有关此问题的任何建议

Definitely go for the modular approach. 绝对要采用模块化方法。 Some of the advantages of taking the modular approach are: 采用模块化方法的一些优点是:

  • It makes your code more readable, ie it's more clear what the PageHandler and FormProcessor do 它使您的代码更具可读性,即,更清楚PageHandler和FormProcessor的功能
  • It makes it easier and more effective to write unit tests on both of your classes 这使得在两个类上编写单元测试更加容易和有效
  • It makes it easier to change the behavior of PageHandler at a later date by using a different implementation of PageHandler 通过使用不同的PageHandler实现,可以更轻松地在以后更改PageHandler的行为。

In general, stick to the idea that one class does one thing; 通常,坚持一个班级做一件事的想法; it's easier to see what you're working with when maintaining your software, as well as making it easier to write (you only have to think about one context at a time then). 在维护软件时,更容易看到正在使用的软件,并且使编写起来更容易(然后您一次只需要考虑一个上下文)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM