假设存在 none,将通用代码移动到基础 class 是否是一种好习惯?

Is it good practice to move common code to base class assuming there is none?

我需要打印定期报告和批量报告。我正在使用 podofo 库。我计划为每个报告使用单独的 classes,但每个 class 都需要下面的一些通用功能(现在在另一个项目的一个 class 中)。

int CPdfBatchReport::CalculateMaxRowsInEmptyPage(void)
{
    int rows = MaxPageHeight / PDF_TABLE_STANDARD_ROW_HEIGHT;

    // because the first will always be the column header in every page, we substrct 1 to account for that
    rows = rows - 1;

    return rows;
}

// Calculates the max rows in current page. The current page is determined 
// by the current x, y position
int CPdfBatchReport::CalculateMaxRowsInCurrentPage(void)
{
    float AvailablePageHeight =  pPage->GetPageSize().GetHeight() - PDF_BOTTOM_MARGIN - y;

    int rows = AvailablePageHeight / PDF_TABLE_STANDARD_ROW_HEIGHT;

    // because the first will always be the column header in every page, we substrct 1 to account for that
    rows = rows - 1;

    return rows;
}


void CPdfBatchReport::StartPage(void)
{
    x = PDF_LEFT_RIGHT_MARGIN;
    y = PDF_TOP_MARGIN;
}

用这个公共代码创建一个基 class 并在派生的 class 中进行实际打印是否有意义?这是一个好习惯吗?

所以基本上我会让基础 class 说 PrintBase 其中包含上述函数和两个派生的 classes PrintBatchReportPrintItemReport 实际上将使用这些功能。

是的,将通用代码放在基础 class 中绝对是个好主意。 "Do not Repeat Yourself" - 干 - 是一种很好的编程风格。避免复制粘贴编程。

您唯一不想在基础class 中包含内容的情况是当它是接口时class。但在这种情况下似乎并非如此。

Yes, absolutely a good idea to put common code in the base class.

我想详细说明@Mats 的回答。就提取到基础 class 中的所有代码都遵循单一职责原则而言,这确实是一个好主意。避免盲目地使用继承来提取公共代码。 Object面向编程不止于此

想想责任。在许多情况下,您应该更喜欢组合而不是继承。您真的需要 parent class 来完成您的任务吗?可能是,现有功能跨越多个职责,可以拆分为多个 class,您的 PrintBase 可以传入或在其中实例化。

这似乎是一个非常合理的解决方案。在这种情况下,您将继承一个通用实现,因此我强烈建议私有继承而不是 public。然后,您只需实例化正确的 child class 即可完成工作。这当然比在多个 class 中复制代码更好。

另一种选择是将通用 parameters/functionality 封装到第三个 class 中,并让每个特定报告都具有其中一个 class 按值分配各种职责给帮助者 class.