是否应在基础类和派生类之间共享特定比例的成员?

时间:2010-11-05 21:37:55

标签: class-design oop member-variables

我正在为我正在为我的课程编写的应用程序设计类,我有两个类听起来好像它们应该是一个基类派生类,并确实共享两个成员变量,而我的问题是它们每个都有七个成员变量而没有操作。

这些类的结构的原因是我正在构建一个RSS阅读器,我打算让这两个类在feed上保存数据。第一个将保存Feed本身的数据,例如源URL,rss.xml文件在本地存储上的位置,上次更新订阅源的时间等。第二个将保存有关其中包含的文章的信息。 feed等发布日期/时间和基于发布日期的整数索引,用于按时间顺序对文章进行排序。

class feed
{
    string title;
    string description;
    string feed_url;
    string local_location;
    string channel;
    bool feed_is_changed; // This is a flag that will be raised and lowered
      // when the feeds are being refreshed
    double last_updated; // The last update date/time will be converted to a
      //standardised double value
}

class feed_item
{
    string title;
    string description;
    double pub_time;
    double pub_time_in_sec; // I'm separating the seconds so they can be used
      // for a 'sub-index' when there are multiple feeds with the same pubtime
      // (there are restrictions on the data types we are allowed to use
      // (concocting work-arounds will aid in understanding, etc))
    double pub_date;
    int pub_year;
    int order_in_list; // The index that will be calculated from pub_time,
      // pub_date, etc
}

上面的代码不完整,我目前只识别变量和函数,私有/公共位一旦完成就会出现。从上面的代码中可以看出,共享的唯一两个变量是 title description。

我不确定是否值得将它们作为实体库对并且只是停用五个不相关的变量,如果它们更有效地使它们完全独立的类,或者这是一个完全情境化的关注,并且它无论哪种方式都可以争论。我担心的是代码可能难以维护和扩展,但是一种方法或另一种方法可能存在固有的执行开销。对此有任何想法和建议将非常感激。

3 个答案:

答案 0 :(得分:2)

feed_item不是Feed,因此Liskov substitution principle失败,不应该是子类。我应该检查你的耳朵 - 这对类绝对听起来不像它们应该是子类。

偶尔(非常,偶尔)实现继承是个好主意,但通常最好通过将共享部分提取到单独的类中并在两个实现中使用它来完成。在这里,这绝对是一个可怕的想法 - 没有很好的代码共享,所以好处最多是模糊的。保持代码简单!

答案 1 :(得分:1)

只有一个派生类?然后几乎可以肯定继承是错误的设计。

继承是有限的,并且这些限制通常不会出现,直到后来使决策更加昂贵。

我的经验法则是避免继承,除非并且直到我能够做出明确和令人信服的案例来使用它。

答案 2 :(得分:1)

如果你真的想要一个基类:

struct NamedItem {  // or maybe just "Item"
  string title;
  string description;
};

struct Feed : NamedItem {/*...*/};
struct FeedItem : NamedItem {/*...*/};

或者,通常首选并且在这种情况下更适合使用遏制:

struct ItemInfo {
  string title;
  string description;
};

struct Feed {
  ItemInfo info;
  //...
};
struct FeedItem {
  ItemInfo info;
  //...
};

特别是,如果你不知道如何在不知道派生类型的情况下使用“NamedItem”,那么使用继承是没有意义的。

相关问题