Search code examples
c++oopinheritancesingle-responsibility-principle

oop inheritance of method vs making object only to call method in class which invoke it


I have problem with judge witch approach is better from design, clean code == good practice.

I load some data from files on start-up of my program and structure of classes looks like this: enter image description here

To be more specific IngredientFromXmlReader, PizzaReader, DrinksFromXmlReader do all job internally, without any data putted from DataFromFileLoader .

The question mark is what with DataFromFileLoader class it should inherit from PizzaReader, IngredientFromXmlReader, DrinksFromXml and have method loadMenuFromFiles like this:

 private void loadMenuFromFiles()
{
    this->loadIngredientsFromXml();
    this->loadPizzasFromXml();
    this->loadDrinksFromXml();    
}

This approach:

  • looks more clean for me,
  • don't create not needed objects,
  • and DataFromFileLoader not looks more crowded, then second approach, because methods are implemented in parent classes.

Or just do it how I done it right know, they all have to implement public method loadXml(), which is virtual method of AbstractReaderFromXml. And then I create object which invoke method.

private void loadMenuFromFiles()
    {
        IngredientFromXmlReader ingreRead;
        ingreRead.loadXml();
        PizzaReader pizzaRead;
        pizzaRead.loadXml();
        DrinksFromXmlReader drinksRead;
        drinksRead.loadXml();   
    }

Why I choose this:

  • it's more stick to single responsibility principle, the responsibilities are more separated, what is advantage,
  • i don't give a chance to invoke this method in places, where is not needed, cause I need object to do so,

The third option is to make static this all internally method of these 3 classes, but I don't like it so much. It's seems to me much heavier for application and I try to avoid it. For sure this is the option.

What approach is better ?

The last thing, if this question fit to stackoverflow or maybe it should be put on

https://softwareengineering.stackexchange.com/


Solution

  • Problem description in this question looks unclear to me. But I would strongly recommend against diamond inheritance in this case.

    Inheritance demonstrates IS-A connection. And PizzaReader does not actually look like FileOpener to me. PizzaReader makes use of FileOpener to open files, right? And that means this is a great example of replacing inheritance with composition.