This Atom is Under Construction

One of the most compelling reasons for object-oriented programming is code reuse.

You may first think of “reuse” as “copying code,” and this is equally easy to do in any language. But it doesn’t work very well. As time passes, your solution evolves, so it’s important to apply changes to only one common place instead of promoting them to every copied piece of code.

In object-oriented programming you reuse code by creating new classes, but instead of creating them from scratch, you use existing classes that someone has already built and debugged. The trick is to use the classes without soiling the existing code.

Inheritance is one way to achieve this, and the compiler does most of the work. It creates a new class as a type of an existing class. You literally take the form of the existing class and add code to it without modifying the existing class. Inheritance is one of the cornerstones of object-oriented programming, and has additional implications explored in the Polymorphism atom.

You can also choose a more straightforward approach, by creating objects of existing classes inside your new class. This is called composition, because the new class is composed of objects of existing classes. You’re reusing the functionality of the code, not its form.

End of sample. See for full early-access book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.