0

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

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

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
}

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

我不确定是否值得将它们设为实体基对并仅停用五个不相关的变量,是否将它们完全分开的类更有效,或者这是否完全是情境问题,并且可以争论无论哪种方式。我担心的是代码可能难以维护和扩展,但一种方法或另一种方法可能存在固有的执行开销。对此的任何想法和建议将不胜感激。

4

3 回答 3

2

feed_item 不是提要,因此它不符合Liskov 替换原则,不应该是子类。我应该检查一下你的耳朵——这对类绝对不应该是子类。

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

于 2010-11-06T12:26:17.450 回答
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”而不知道最派生的类型,那么使用继承是没有意义的。

于 2010-11-06T15:23:08.677 回答
1

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

继承是有限制的,而这些限制通常直到后来做出更加昂贵的决定时才会出现。

我的经验法则是避免继承,除非并且直到我能够提出一个清晰且令人信服的案例来使用它。

于 2010-11-05T21:53:51.407 回答