tags:

views:

94

answers:

4

I recently encountered a situation in some code I am working on that doesn't make sense to me. A set of classes are inheriting from a base class purely to share some methods in the base class. There is no method overriding, just child classes calling methods from the parent class.

It seems to me that this would be better modeled by having the child classes reference the parent class rather than inheriting from it, which I think would reduce unnecessary complexity. Is this reasonable, or am I missing some benefit of using inheritance like this?

+2  A: 

You are correct. Unfortunately inheritance is used a lot when it is not actually needed.

If there isn't is-a relationship between the child and parent class then inheritance should not be used.

Tuomas Pelkonen
A: 

I can suppose that the inheritance you can observe is just a result of refactoring.

Roman
Not the best kind of refactoring, since it doesn't increase readability ;-)
gruszczy
Anyway it's much better than copy/pasted code which was before this refactoring.
Roman
+3  A: 

If the parent class methods are there purely as 'utilties' then yes, I agree.

The question (for me at least), would be if the parent class could be modified in the future to have benefit. Meaning, what is the current relationship logically? If it's an "is a" between child and parent then leave it. If the parent is just a collection of methods, refactor to a utility class or use delegation.

derivation
+3  A: 

Inheritance can be used (and abused !) in different ways. Here is the three big categories.

Conceptual hierarchy:

conceptually related classes can be organized into a specialization hierarchy :

  • people, employees, managers
  • geometric objects ...

Polymorphism:

Objects of distinct, but related classes may be uniformly treated by clients

  • array of geometric objects

Software reuse:

Related classes may share interfaces, data structures or behaviour.

  • geometric objects ...

For a complete study of the different forms of inheritance, read On the notion of inheritance.

The case that you mention, is software reuse. There is no is-a relationship, at most a has-a relationship. The goal is mostly to reuse the same code.

As you suggest, this can be refactored with delegation, or even into a utility class is the method are essentially static.

ewernli