Question

In: Computer Science

Explain why composition is generally preferred to inheritance for achieving code reuse.

Explain why composition is generally preferred to inheritance for achieving code reuse.

Solutions

Expert Solution

Favor composition over inheritance is one of the popular object-oriented design principles, which helps to create flexible and maintainable code in Java and other object-oriented languages. On composition, a class, which desire to use the functionality of an existing class, doesn't inherit, instead, it holds a reference of that class in a member variable, that’s why the name composition. Inheritance and composition relationships are also referred to as IS-A and HAS-A relationships.

  • In OOP, the IS-A relationship is completely inheritance. This means, that the child class is a type of parent class. For example, an apple is a fruit. So you will extend fruit to get an apple.
  • On the other hand, composition means creating instances that have references to other objects. For example, a room has a table. So you will create a classroom and then in that class create an instance of a type table.

Composition becomes preferable for a number of reasons:

  1. Though both Composition and Inheritance allows you to reuse code, one of the disadvantages of Inheritance is that it breaks encapsulation. If subclass is depending on superclass behavior for its operation, it suddenly becomes fragile. When behavior of super class changes, functionality in sub class may get broken, without any change on its part. If you have used Composition in favor of Inheritance you won't face this problem and your class would have been more robust because you are not relying on super class behavior any more.
  2. Composition offers better test-ability of a class than Inheritance. If one class is composed of another class, you can easily create Mock Object representing composed class for sake of testing. Inheritance doesn't provide this luxury. In order to test derived class, you must need its super class.
  3. Composition allows you to delay the creation of components until they are needed, or to never create them at all if they are not needed. Perhaps your Car is driving in the day, and the lights aren’t needed, so they never even need to be created.
  4. It is more natural to build business-domain classes out of various components than trying to find commonality between them and creating a family tree. For example, an accelerator pedal and a steering wheel share very few common traits, yet both are vital components in a car. What they can do and how they can be used to benefit the car is easily defined. Composition also provides a more stable business domain in the long term as it is less prone to the quirks of the family members. In other words, it is better to compose what an object can do (HAS-A) than extend what it is (IS-A).

Prefer composition over inheritance and you’ll have more flexible, extensible, and testable code.


Related Solutions

Explain why composition is generally preferred to inheritance for achieving code reuse.
Explain why composition is generally preferred to inheritance for achieving code reuse.
Explain why firms choose to decentralize and give an example Explain why NPV is generally preferred...
Explain why firms choose to decentralize and give an example Explain why NPV is generally preferred over IPR when choosing among competing or mutually exclusive project. Why would managers continue to use IRR to choose among mutually exclusive projects?
Describe and contrast the features of common stock and preferred stocks. Explain why dividend payments generally...
Describe and contrast the features of common stock and preferred stocks. Explain why dividend payments generally follow changes in earnings. List of important dates for dividend payments and enumerate the advantages of dividend reinvestment plans. What tenet of investing do dividend reinvestment plans subscribe to? What are the similarities and differences between a stock split and a stock dividend? Why would a company do them?
A- Explain the term "waste reuse" and mention the main difference between waste reuse and waste...
A- Explain the term "waste reuse" and mention the main difference between waste reuse and waste recycle A- Briefly describe what you know about Ozone depletion and Global warming.and Name the major risks caused by a SOx on humans? -What air pollution control device is better in removing SO4? Draw the device and label all the important components. A- List all the three Exposure Pathways to consider in risk assessment. Draw the Inverted Hierarchy of Waste Minimization and give one...
Question: Why is the accrual basis of accounting generally preferred over the cash basis?
Question: Why is the accrual basis of accounting generally preferred over the cash basis?
Reuse the code to prompt the user for a specific day, test whether it is within...
Reuse the code to prompt the user for a specific day, test whether it is within range, and then output the estimated concrete strength from the fitted curve using polyval. Run your function from the command window for 2 different days to test the functioning of your code. The program should preferably loop until the user asks to exit. where x = days y = rain (mm) x = [0 1 2 3 7 14 28]; y = [0 4...
Consider the DataSource class in below code. Explain how inheritance is intended to be used with...
Consider the DataSource class in below code. Explain how inheritance is intended to be used with this class. Does this represent a good use of inheritance? Explain your answer // Base class for game configuration public abstract class DataSource {     private Graph map;     private HashMap <String,Room> rooms;     private ArrayList <Entity> entities;     private Player player;     protected HashMap < String, List<String[]> > tables;     // constructor     public DataSource() {     }     // Connect to the...
Write the code to implement the concept of inheritance forVehicles. You are required to implement inheritance...
Write the code to implement the concept of inheritance forVehicles. You are required to implement inheritance betweenclasses. You have to write four classes in C++ i.e. one superclass, two sub classes and one driver class. Vehicle is the super class whereas Bus and Truck are sub classesof Vehicle class. Transport is a driver class which contains mainmethod. Detailed description of Vehicle (Super class): The class Vehicle must have following attributes: 1. Vehicle model 2. Registration number 3. Vehicle speed (km/hour)...
1. Implement a method that meets the following requirements: (a) Do not reuse any code for...
1. Implement a method that meets the following requirements: (a) Do not reuse any code for the following: i. Try to write this method with as few lines of code as you can ii. Sorts a group of three integers, x,y and z, into decreasing order (they do not have to be in a sequence). iii. Assume the value in x is less than the value in z. You can also assume there are no duplicates among x, y and...
why do companies issue preferred stock, explain why.
why do companies issue preferred stock, explain why.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT