Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the disadvantages of using inheritance as a way of reusing code? [closed]

What are the disadvantages of using inheritance as a way of reusing code?

like image 380
inglor Avatar asked Jul 20 '10 21:07

inglor


People also ask

Which is one disadvantage of inheritance?

Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly coupled. This means one cannot be used independent of each other.

What are the disadvantages of inheritance in Java?

Disadvantage: The inheritance relationship is a, tightly coupled relationship , there will be tight bonding between parent and child. If we change code of parent class it will get affects to the all the child classes which is inheriting the parent code.

How does inheritance achieve code reuse?

Implementation inheritance is described as a way to achieve code reuse. This works by defining methods and variables in a class that is then inherited by other classes. Those other classes are said to be derived from the original class, and the original class is said to be their base class.

What are the advantages of reusing code?

So, you can reuse code when it can be: Easily extended and adapted for the new application. Ported to different hardware if needed. Shown to be free from defects or problems that affect the reliability, safety, or security of the new application.


1 Answers

Using inheritance to achieve code reuse suffers from the following problems:

  1. You cannot change the reused behaviour at runtime. Inheritance is a compile-time dependency, so if a GameClient class inherits from TCPSocket to reuse the connect() and write() member functions, it has the TCP functionality hardcoded. You cannot change this at runtime.

  2. You cannot replace the reused behaviour from the outside for the sake of testing. If a GameClient class inherits from TCPSocket so that it gets write() (for writing data to a socket), you cannot exchange this code from the outside. You cannot plug in a different write() function which logs all data which GameClient wants to write to a file or so.

  3. You are dependant on multiple inheritance for all but the most simple applications. This opens the door for diamond shaped inheritance trees which increase the code complexity a lot.

Preferring composition over inheritance to reuse code avoids all these issues.

like image 131
Frerich Raabe Avatar answered Oct 01 '22 18:10

Frerich Raabe