Scratch, Inheritance or Composition

This post offersadvantages and disadvantages of writing code from scratch versus using objectoriented techniques.   

When approaching a softwareproject, the developer must determine the most appropriate method ofdevelopment.  This involves many choices,including what objects are relevant, the classes for those objects, and whetherto code those classes from scratch, or to utilize object-oriented techniqueslike inheritance or composition (Deitel & Deitel, 2012, pp. 360-361).

WritingFrom Scratch

First, this post looks at theconcept of writing from scratch, a term “which comes from 19thCentury sports terminology” (Schach, 2011, p. 59).  Generally speaking, as the term is used inprogramming today, the terms means to start with nothing.  The advantages and disadvantages of writingfrom scratch include:

Advantage: When approaching asoftware project, the development process usually involves a process known aspseudocode.  During this process, thedeveloper formulates the algorithms that must be used as part of the project,focusing more on the goal to be achieved each logical step as opposed to theprogramming code itself (Deitel & Deitel, 2012, p. 113).  Traditionally, developing code from scratch isthe next step in development after pseudocode and it is perhaps the best way toensure that the algorithm is constructed exactly as prescribed. 

Code that is quicklyimplemented, or uniquely vital to the program, would be good candidates forwriting from scratch.  Consider, forexample, pseudocode that merely calls for the creation of a integer countervariable.  The simplest, and best,implementation is to simply write that code by scratch.

Disadvantage: While writingcode from scratch may seem to be a good, and at times best, approach to coding,when writing code from scratch the developer misses out on potential time savingsfrom utilizing object-oriented tools such as inheritance and composition.  Generally, these include reduced maintenance,modeling of the real world which has already been completed, and improvedreliability (Burleson, 2019). 

Consider, for example, aprogram that used random numbers in various forms such as random integers,random decimals, random ranges of numbers, or even random collections ofnumbers.  Programming the code to producethese variations could take substantial amounts of time.  But Java has a ready solution for this need –the Class java.util.Random (Oracle, 2019), which when imported into a Classprovides many useful methods to produce a variety of random objects.    

Inheritance

Inheritance, where the classto be constructed takes on the attributes and methods of another class, isdescribed as an ‘is-a’ relationship (Deitel & Deitel, p. 361).  Through inheritance, a super-class makesavailable all of its attributes and methods for use in the sub-class.  Because of the visibility of super-classattributes and methods, inheritance is sometimes referred to as “white-boxreuse” (Gamma, Helm, Johnson, & Vlissides, 1995, p. 19).

For example, a car ‘is a’vehicle, so the Car class could be constructed as a sub-class of thesuper-class Vehicle.  This application isfar more than imported static methods and values from another Class such asRandom mentioned above.  In this case,the super-class passes down all attributes and methods to the sub-class.  If Vehicle is the super-class, for example, theattributes of the class might include number of wheels, type of power needed,or number of passengers.  When the classCar inherits the Vehicle class, Car takes on the attributes of Vehicle but thenadds attributes such as model, make, and gas mileage. 

Advantage:  Using inheritance, “time is saved duringprogram development by basing new classes on existing proven and debuggedhigh-quality software” (Deitel & Deitel, 2012, p. 360).  Stephen R. Schach suggests that the timesavings for program coding along with all the other benefits of inheritance,can be summarized as follows: “Underlying all these reasons is that awell-designed object, that is, an object with high cohesion and low coupling,models all of the aspects of one physical entity” (2011, p. 218).  Schach goes on to explain that the power isthat the vast majority of the implementation is hidden, consisting ofattributes and methods at work in the super class, which is the essence of lowcoupling (2011, p. 218).

Using the car example, Carinherits Vehicle, suppose that Vehicle contains a method called paintVehicle(StringcolorCode, int paintCost).  The method changesthe vehicle attribute vehicleColor and addes paintCost to the attributevehicleCost.  When Car inherits Vehicle,there is no need to program a paintCar() method.  The paintVehicle() method can be applied toCar objects once Car inherits Vehicle. 

Disadvantage:  A problem known as fragile base Classpresents a risk for all implementations of inheritance (Schach, 2011, p. 219).  This often arises after the software iscomplete, and is already in use, and is associated with changes in one orseveral super-class attributes or methods. Modifications to super classes, unless anticipated, will feed down tothe sub-class attributes and methods.  Becauseinheritance exposes the sub-class to details of the parent’s implementation, “it’soften said that inheritance breaks encapsulation” (Gamma, Helm, Johnson, & Vlissides, 1995, p. 19).

Continuing the Car inheritsVehicle example, consider a software project which needs to analyze the mileageof different model cars.  Car inheritsVehicle, attributes and methods, and then adds attributes for the unique Carcharacteristics like model, make, manufacturer, etc.  Suppose then, at a later date, the keepers ofthe Vehicle class decide to add a Boolean Vehicle attribute called isGreenwhich indicates whether or not the vehicle is environmentally friendly.  They decide, on their own accord, that everyVehicle object where isGreen is unknown or undefined will be set to false.  Because of this change in the parent class,Car will need to modify its constructor or risk that every car be assignedfalse for the isGreen attribute. 

Composition

Composition occurs when multipleclasses contribute their attributes and methods to a single class, and if theresultant class would cease to exist and if the aggregate class is deleted thenso are the contributing classes (Schach, 2011, p. 575).  Composition is used when a composition classcan be said ‘has a’ component class attributes and methods. 

Object composition provides analternative to class inheritance (Gamma, Helm, Johnson, & Vlissides, 1995, p. 19).  With inheritance functionality is made, inlarge part, with static methods extended from the super-class to thesub-class.  Composition, on the otherhand, offers functionality to the receiving class through object attributes andobject methods.  Using composition, nointernal details of the contributing class need be known.  As a result, in contrast to the white-boxlabel for inheritance, composition is sometimes referred to as “black-boxreuse” (Gamma, Helm, Johnson, & Vlissides, 1995, p. 19).

To illustrate composition, acar ‘has a’ steering wheel, so a proper use of composition would be to use aSteeringWheel class to construct a steeringWheel object for use in the Carclass (Deitel & Deitel, 2012, p. 361).   Of course, other classes like Engine, Wheels,Seats, etc. would contribute to the greater composition class so that, uponcompletion, the Car class would be comprised of objects from each of itscomposition classes.

Advantage:  With composition, objects are accessed solelythrough their interface, so that exposure to the super-class is limited andencapsulation is maintained (Gamma, Helm, Johnson, & Vlissides, 1995, p. 19).

Continuing the Car illustration,we consider that the Car is composed of objects from several different classeslike SteeringWheel, Engine, Seats, GasTank etc. These supporting classes have constructors and object methods which canbe used for the composition of the Car class. However, the programming of the Car class carefully defines theinterface, offering control of how the attributes of supporting classes impactthe Car composition. 

Disadvantage:  With composition, objects are created from avariety of different classes for use together in the program.  This leads to the requirement that objects“respect each other’s interfaces, which in turn requires carefully designedinterfaces that don’t stop you from using one object with many others” (Gamma, Helm, Johnson, & Vlissides, 1995, p. 20.).

The Car illustration continuesto offer a meaningful example.  Considerthe Car class being composed in part by the classes Engine and GasTank.  Obviously, the GasTank and Engine classesproduce objects which rely on one another. The relationship could prove problematic if not accounted for in specialcases, like when the engine type changes from gas-fueled to electric, i.e.there is no need for a GasTank object.  Notonly must each class interface with the composition class Car, but once therethey must be defined well to co-exist as needed. 

References                                          

Burleson, D. (2019, March 11). Advantages and disadvantages of object-oriented approach. Retrieved from BC Burleson Consulting

Deitel, P., & Deitel, H. (2012). Java: How to Program 9th Edition. Boston: Prentice Hall.

Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Boston: Addison-Wesley.

Hayes, D. (2019, January 22). Is WordPress object-oriented? A thorough exploration. Retrieved from WPShout.Com

Oracle. (2019, March 11). Class Random. Retrieved from Docs.Oracle.com

Paul, J. (2017, June 4). 5 Reasons to use composition over inheritance in Java and OOP. Retrieved from JavaRevisited

Schach, S. (2011). Object-Oriented and Classical Software Engineering, 8th edition. New York: McGraw Hill.

Leave a Comment

Your email address will not be published. Required fields are marked *