Home > database >  Would this be considered bad practice in OOP?
Would this be considered bad practice in OOP?

Time:09-28

For instance, I have a class A. This class has children that inherit from it Aa, Ab, Ac, and Ad.

Say Aa and Ab require a similar function that adds numbers and another function that subtracts, the only difference is the values they put in. While Ad and Ac share common functions with Aa and Ab, they do not need the add and subtract functions at all. Would it be bad practice if I were to declare this function in class A, instead of declare it for Aa and Ab separately?

Is this better:

float Aa::AddNumbers(){...}
float Aa::SubtractNumbers(){...} 

float Ab::AddNumbers(){...}
float Ab::SubtractNumbers(){...} 

Than this:

float A::AddNumbers(){...}
float A::SubtractNumbers(){...}

To me it just seemed redundant to implement add and subtract four times, but at the same time I wonder if it defeats the purpose of OOP if Ac and Ad can't benefit from those functions. I am currently in this same pickle with the program I'm working on and I'm not sure what would be a better approach/what weighs more (implement 4 times in their respective classes or implement once in the parent but only can be useful to a few classes)

CodePudding user response:

I would look into using virtual/abstract functions to potentially solve the problem. A lot of it will depend on what you may need class A for and then the children classes.

Also remember that overloading/overriding are options availible.

Lastly, if you are worried about modularity. You could use a single parent function wherein you pass some data struct like a vector. This vector is populated with child data. Add another param or enum for different operations to perform. Use switch statement on enum, then iterate over vector as desired performing said operations.

CodePudding user response:

Apparently Aa and Ab share some functionality which does not exist in A and, consequently, in other classes descending from it. So may be you just need to introduce another intermediate class Aq derived from A, and then derive Aa and Ab from Aq....?

  • Related