Search code examples
c++ooparchitecturecode-reuse

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


I need to print regular report and a batch report. I am using podofo library. I plan to use separate classes for each report but each class will be needing some common functions below (right now in one class in another project).

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;
}

Does it make sense to create a base class with this common code and do the actual printing in a derived class? Is it a good practice?

So basically I will have the base class say PrintBase with the above functions in it and two derived classes from it PrintBatchReport and PrintItemReport which will actually be using those functions.


Solution

  • Yes, absolutely a good idea to put common code in the base class. "Do not Repeat Yourself" - dry - is a good programming style. Avoid copy-paste programming.

    The only time you don't want content in a baseclass is when it's an interface class. But that doesn't appear to be the case in this situation.