继承还是不继承

问题描述:

我有三个对象;行动,问题和风险.这些都包含大量的公共变量/属性(例如:描述,标题,到期日,提出者等)和一些特定字段(风险具有概率).问题是:

I have three objects; Action, Issue and Risk. These all contain a nunber of common variables/attributes (for example: Description, title, Due date, Raised by etc.) and some specific fields (risk has probability). The question is:

  1. 我应该单独创建3个 动作,风险和问题类别 包含重复字段.

  1. Should I create 3 separate classes Action, Risk and Issue each containing the repeat fields.

创建父类"Abstract_Item" 包含这些字段和 对它们进行操作,然后执行 行动,风险和问题子类 Abstract_Item.这将坚持 DRY负责人.

Create a parent class "Abstract_Item" containing these fields and operations on them and then have Action, Risk and Issue subclass Abstract_Item. This would adhere to DRY principal.

我的观点

比方说,如果您使用继承.在一段时间内,您具有仅 Action Issue 而不是 Risk 通用的新属性.您将如何处理?如果您将它们放在父项下,那么Risk会继承不相关的内容(Liskov替代原理敲门?).如果您分别将操作"和风险"分别放置,则您将破坏DRY,这是开始继承的最初原因.要点是重用性,这是不好的.如果没有"is-a",那么最好不要使用它,如果您有疑问,那么就没有真正的"is-a".

Let's say, if you used inheritance. Over a period you have new attributes that are common to only Action and Issue but not Risk. How will you handle this? If you put them under parent then Risk is inheriting stuff that is irrelevant (Liskov Substituon Principle knocking?). If you put then in Action and Risk separately then you are breaking DRY, the initial reason why you started inheritance. Point is Inhertence for re-use is bad. If there is no "is-a" then better not use it and when you are in doubt then there is no real "is-a".

我的偏好

还有其他实现DRY的方法,如下面的示例代码所示.有了新的属性,我又是另一个 Common2 ,如果它们不适用于所有3个类,则新的行为就是新的 CommonBehavior2 .如果只是更改现有的 Common CommonBehavior

There are other ways of achieving DRY as shown in below example code. With this addition of new properties my be another Common2, addition of new behavior is new CommonBehavior2 if they are not applicable to all 3 classes; if they are then just change existing Common and CommonBehavior

public class Common implements CommonBehavior
{
    String Description;
    String title;

    public void f() {}
}

public interface CommonBehavior
{
    void f();
}

public class Action implements CommonBehavior
{
    private Common delegate;

    public void f()
    {
        delegate.f();
    }
}

还用另一个实际示例来查看我对类似问题的回答

Also look at my answer to a similar question with another practical example Design pattern to add a new class