开发者

Using inheritance purely to share common functionality

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 开发者_StackOverflow中文版am I missing some benefit of using inheritance like this?


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.


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.


Inheritance can be used (and abused!) in different ways. Here are 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 if the methods are essentially static.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜