Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should composition be used exclusively over inheritance or are there cases when it should not?

In the example I'm thinking of I have about 4 lines of code that could be encapsulated by a function, and this function will surely be used in other classes in the same hierarchy.

I have the following options for reusing that code:

  1. Copy paste the function around to the classes that need it.
  2. Make a base class for the classes that need the function and put it there.
  3. Make a class that contains the function which gets passed into the classes that need it through DI or is just a member of the class. (seems like major overkill)
  4. Make a static utility class and put that method in it.

I definitely wouldn't do 1 or 4. I would have done 2 in the past but I'm trying to keep to the composition over inheritance principle so I'm leaning towards 4 however it seems like a lot for something that will most likely never be used outside the hierarchy and is only 4 lines. I know this is very nitpicky but I want to figure out the right way to do it.

like image 568
fordeka Avatar asked Aug 30 '12 19:08

fordeka


1 Answers

Inheritance was created for a reason. The fact that it has been overused doesn't mean that it doesn't have legitimate uses. The key is that whether you use it should not depend on whether you can get easy reuse out of it, but whether it makes sense for it to belong to the base class, based on what your base class represents.

Without better understanding what your classes are, and what the method is that you're trying to reuse, I can't give specific advice in your particular case. But think of it this way: When you say it will "most likely never be used outside the hierarchy," is that because it purely just doesn't make sense outside of that hierarchy? Or is it just that you don't think somebody's going to build something that happens to use this feature, even though it could conceivably make sense outside of the hierarchy?

If this method would make any sense outside of the specific hierarchy you're talking about, I would suggest approach #3.

And of course, all of this assumes that your class hierarchy is really a hierarchy in the first place. Another common abuse of inheritance is when people force a hierarchy on objects that don't need to be hierarchical in the context of their application.

like image 54
StriplingWarrior Avatar answered Sep 18 '22 00:09

StriplingWarrior